2015-11-13 27 views

risposta

3

Il BsonWriter di Newtonsoft.Json è obsoleto.

è necessario aggiungere un nuovo NuGet-pacchetto chiamato Json.NET BSON (basta cercare newtonsoft.json.bson) e lavorare con BsonDataWriter e BsonDataReader invece di BsonWriter e BsonReader:

public static string ToBson<T>(T value) 
{ 
    using (MemoryStream ms = new MemoryStream()) 
    using (BsonDataWriter datawriter = new BsonDataWriter(ms)) 
    { 
     JsonSerializer serializer = new JsonSerializer(); 
     serializer.Serialize(datawriter, value); 
     return Convert.ToBase64String(ms.ToArray()); 
    } 

} 

public static T FromBson<T>(string base64data) 
{ 
    byte[] data = Convert.FromBase64String(base64data); 

    using (MemoryStream ms = new MemoryStream(data)) 
    using (BsonDataReader reader = new BsonDataReader(ms)) 
    { 
     JsonSerializer serializer = new JsonSerializer(); 
     return serializer.Deserialize<T>(reader); 
    } 
} 
2

https://www.nuget.org/packages/Newtonsoft.Json

PM> Installa-Package Newtonsoft.Json -Version 7.0 .1

using Newtonsoft.Json.Bson; 
using Newtonsoft.Json; 

class Program 
    { 
     public class TestClass 
     { 
      public string Name { get; set; } 
     } 

     static void Main(string[] args) 
     { 
      string jsonString = "{\"Name\":\"Movie Premiere\"}"; 
      var jsonObj = JsonConvert.DeserializeObject(jsonString); 

      MemoryStream ms = new MemoryStream(); 
      using (BsonWriter writer = new BsonWriter(ms)) 
      { 
       JsonSerializer serializer = new JsonSerializer(); 
       serializer.Serialize(writer, jsonObj); 
      } 

      string data = Convert.ToBase64String(ms.ToArray()); 

      Console.WriteLine(data); 
     } 
    } 
+0

Aggiornamento per gli utenti desiderare di utilizzare questo: 'BsonWriter 'è obsoleto, controlla la mia risposta –

3

B ehold! C'è un modo molto più semplice per farlo:

BsonDocument doc = BsonDocument.Parse("{\"your\": \"json\", \"string\": \"here\"}"); 
2

durante l'utilizzo json nel mio progetto ho notato che ci sono modo semplice e dolce per convertire json in un documento bson.

string json = "{\"Name\":\"Movie Premiere\"}"; 
BsonDocument document = BsonDocument.Parse(json); 

ora è possibile utilizzare document come SBB ovunque.

Nota- Sto utilizzando questo document da inserire nel database MongoDb.

Sperando che questo ti possa aiutare.

Problemi correlati