Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 990
Ben Foster Avatar asked May 19 '14 09:05

Ben Foster


2 Answers

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.

like image 174
Neil Lunn Avatar answered Oct 18 '22 05:10

Neil Lunn


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>()
like image 7
Louie Almeda Avatar answered Oct 18 '22 04:10

Louie Almeda