JSON array to ExpandoObject via JSON.NET

穿精又带淫゛_ 提交于 2019-12-10 17:47:40

问题


I am using the following approach to convert most of my API JSON results into an object:

public void ExpandoObject()
{
    var sampleDATA = Sample.Create();
    var json = JsonConvert.SerializeObject(sampleDATA);

    var expConverter = new ExpandoObjectConverter();
    dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, expConverter);

    var a = obj.A;

    var b = obj.B;

    var c = obj.C; //and so on...
}

However, I run into a strange situation with this format of JSON...

[
    {
        "id": 42,
        "name": "example name",
        "member_count": 42,
        "created_date": "example created_date",
        "last_update": "example last_update",
        "last_reset": "example last_reset"
    }
]

Because it is an array, how can I access the items, the ExpandoObject is supposed to be an IDictionary of sorts.

Anyone had experience with this?


回答1:


Use List<ExpandoObject> when deserializing:

var expConverter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<List<ExpandoObject>>(json, expConverter);

Your obj variable will be list of expando objects that you can iterate.



来源:https://stackoverflow.com/questions/22464751/json-array-to-expandoobject-via-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!