gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:12:28 25 4
gpt4 key购买 nike

我在访问 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 类?

最佳答案

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

例如:

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

关于c# - 将json的动态属性读入.net C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19676295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com