如何使用Json.NET将JSON转换为BSON

时间:2015-11-13 03:34:22

标签: c# json.net bson

我有一个包含JSON的字符串。我对这个JSON唯一了解的是它是有效的。如何将此字符串转换为BSON?

5 个答案:

答案 0 :(得分:9)

BsonWriter的{​​{1}}已过时。

您需要添加名为Newtonsoft.Json的新nuget-package(仅搜索Json.NET BSON)并使用newtonsoft.json.bsonBsonDataWriter代替BsonDataReader BsonWriter

BsonReader

答案 1 :(得分:4)

我认为这会为你做到这一点

MongoDB.Bson.BsonDocument BSONDoc
= MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);

您还可以查看Serialize to BSONC# - Converting JSON string to BSON document

答案 2 :(得分:2)

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

PM&GT;安装包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);
        }
    }

答案 3 :(得分:2)

看哪!有一种更简单的方法:

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

答案 4 :(得分:2)

在我的项目中使用json时,我注意到将json转换为bson文档的方法很简单。

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

现在你可以在任何地方使用document作为bson。

注意 - 我正在使用此document插入MongoDb数据库。

希望这会对你有所帮助。