I’m using c# to read data from MongoDb and I’ve run into a situation where the data for one of my keys: GoodsList is being read in this form:
"goodsList": [
[
{
"name": "name",
"value": "testName"
},
{
"name": "price",
"value": 32
},
{
"name": "number",
"value": 1
},
{
"name": "id",
"value": 68345
},
{
"name": "cate_id",
"value": 6208
},
{
"name": "image",
"value": "/testimg.png"
},
{
"name": "use_property",
"value": 1
},
{
"name": "props_text",
"value": "standardtext,standardtext2"
},
{
"name": "props",
"value": [
582,
585
]
}
]
]
But I don’t want this, I want it to be read in this format below:
"StatusText": "Finished",
"GoodsList": [
{
"name": "testName",
"price": 32,
"number": 1,
"id": 68345,
"cate_id": 6208,
"image": "/testimg.png",
"use_property": 1,
"props_text": "standardtext,standardtext2",
"props": [
582,
585
]
}
],
"Notes": "this.form.remark",
How can I set the correct format for reading? I’ve tried reading it as BsonArray or BsonDocument or directly as an entity class (GoodsList in entity class as BsonArray or BsonDocument), but it doesn’t work, either I get a conversion error or the result is still the same.
2
Answers
As mentioned in the comment, you should create your own model classes, same goes for
GoodsList
.When you are using
BsonArray
/BsonDocument
and serialize the result, it will show the objects containing theKey
andValue
properties.Your model classes should be as below:
The schema of the document is not very easy to deserialize with C#. However, you can create a custom serializer that retrieves the values. I assume you have a POCO structure similar to the following:
You can implement a custom serializer that deserializes the single
GoodsList
objects like this:Above code uses a DynamicArrayDeserializer to read the array that contains the properties of a
GoodsList
object. It then iterates over the array items and assigns the corresponding properties. At the end, the constructedGoodsList
object is returned.You either need to register the serializer globally or by using an attribute like this:
When reading the documents from the database, the serializer is used; the
goodsList
property that holds an array of arrays is deserialized into anIList<GoodsItem>
.