将 json 的动态属性读取到 .net C# 中

本文关键字:net 读取 属性 json 动态 | 更新日期: 2023-09-27 18:37:21

我在点击 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 属性(本质上是动态的,可以根据提供给 API 的参数具有任何值)映射到我们的 .net 类?

将 json 的动态属性读取到 .net C# 中

您可以将其映射到字典。其中,动态属性是字典的键,对象是字典项的值。

例如:

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"
    } 
}

Js 对象是一个字典,所以你可以映射到字典,键 = 一些属性,值 - .net 代码你想要什么

Dictionary<object,'your data class'>

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

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

然后,您可以遍历或应用其他一些逻辑来读取jSonObject