将json的动态属性读入.net C#

时间:2013-10-30 07:30:58

标签: c# .net json json.net

我在点击API之后得到了json格式:

{
    "7407": {
        "survey_id": "406",
        "device_id": "1",
        "response_time": "2013-10-10 16:14:01",
        "timezone": "0",
        "language_id": "en",
        "response_id": "7407",
        "device_alias": "QR Code App",
        "site_name": "QR Code App",
        "country_name": "United States",
        "state_name": "New York",
        "city_name": "Suffern",
        "zip": "",
        "voucher_name": null,
        "voucher_mode": null,
        "surveyee_name": null,
        "surveyee_email": null,
        "surveyee_phone": null,
        "ques": {
            "": []
        }
    },
    "7408": {
        "survey_id": "406",
        "device_id": "1",
        "response_time": "2013-10-10 16:36:56",
        "timezone": "0",
        "language_id": "en",
        "response_id": "7408",
        "device_alias": "QR Code App",
        "site_name": "QR Code App",
        "country_name": "India",
        "state_name": "Gujarat",
        "city_name": "Ahmedabad",
        "zip": "",
        "voucher_name": null,
        "voucher_mode": null,
        "surveyee_name": null,
        "surveyee_email": null,
        "surveyee_phone": null,
        "ques": {
            "": []
        }
    } }

我正在使用 JSON.Net 来阅读上面给出的json数据。

要将此数据映射到.Net代码,我将需要.net中的类,其名称与json字符串中的名称相同。 但是 json中有一些属性可以是动态的(在我的例子中是“7407”,“7408”等),也就是说这个值可以根据我们传入参数的内容来改变。

我的问题是,我们如何将json属性(它们本质上是动态的,并且可以根据提供给apis的参数具有任何值)映射到.net类?

3 个答案:

答案 0 :(得分:3)

您可以将其映射到词典。动态属性是DictionaryIem的Key,而Objet是DictionaryItem的值。

对于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; }
}

对于这个例子,我简化了你的json。所以它看起来像这样:

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

答案 1 :(得分:0)

Js对象是一个字典,所以你可以用key = some属性和值 - .Net代码映射到Dictionary你想要什么

Dictionary<object,'your data class'>

答案 2 :(得分:0)

我能找到处理这种JSON数据的最好方法是使用JSON.Net库的JObject类。 例如:

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

然后您可以循环或应用其他逻辑来阅读jSonObject