简体   繁体   中英

How to parse a JSON array in C#?

Using the MongoDB C# driver how can I parse a JSON array (string) into BsonDocument[] ?

We would like to store our mongo aggregation pipelines in separate JSON documents so need a way to parse them.

Not a bad idea if that suits your purposes. Yes the C# driver already supports BSON serialization from a JSON string source:

string json = '[
    { "$match: { "foo": "bar" } },
    { "$group": {
        "_id": null, 
        "count": { "$sum": 1 }
    }}
]';

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

So you can pull in your aggregation pipeline strings formatted as JSON and use them or manipulate them as BSON documents.

The accepted answer's result is a BsonArray, if you need a BsonDocument[] you'll do something like

BsonSerializer.Deserialize<BsonArray>(yourJsonString).Select(p => p.AsBsonDocument)

and if you need it as a List<BsonDocument>

BsonSerializer.Deserialize<BsonArray>(yourJsonString).Select(p => p.AsBsonDocument).ToList<BsonDocument>()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM