Reading dynamic attributes of json into .net C#

。_饼干妹妹 提交于 2019-12-06 12:23:46

You could map it to a Dictionary. Where your dynamic property is the Key of a DictionaryIem and the Objet is the Value of your DictionaryItem.

For Exmaple:

public class MyClass
{
    public void readJson)
    {
        var json = "{\"7407\": {\"survey_id\": \"406\",\"device_id\": \"1\",},\"7408\": {\"survey_id\": \"406\",\"device_id\": \"1\",}}";
        Dictionary<int, MyObject> dict = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, MyObject>>(json);
        var count = dict.Keys.Count;
    }
}

public class MyObject
{
    public string survey_id { get; set; }
    public string device_id { get; set; }
}

For this exmaple i simplified your json. so that it looks like this:

{
    "7407": {
        "survey_id": "406",
        "device_id": "1"
    },
    "7408": {
        "survey_id": "406",
        "device_id": "1"
    } 
}

Js object is a dictionary, so you can map to Dictionary with key = some attribute, and value - .Net code what you want

Dictionary<object,'your data class'>

The best way I could find handling this kind of JSON data is by using JObject class of the JSON.Net library. For eg:

Newtonsoft.Json.Linq.JObject jSonObject = JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(somejsonstring);

and then you can loop through or apply some other logic to read jSonObject

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