[英]Importing Json to objects in C#
我一直在尝试将对象列表从 Json 导入到 C#。
Json结构为:
"meta": {
"file_version": 11,
"machine_number": 210xxxxx,
"software": {
"software_date": "",
"software_version": ""
},
"saved": {
"user": "Bxxxxxx",
"date": "20220810",
"time": "132156"
},
"application": {
"name": "Support",
"type": "xxxxx_Support"
},
"validity": {
"machine_model": "xxx",
"arm_assembly": "xxx",
"boom_pedestal": "xxx"
}
},
"data": {
"data532": {
"number": 54,
"name": "Abstützung vorne - zulässige vertikale Beinkraft (P1.Q1)",
"format": 0,
"digit": 0,
"unit": 10,
"category": 0,
"min": 0,
"max": 1000000,
"value": 225000,
"hexvalue": "0x00036EE8",
"binvalue": "0b00000000000000110110111011101000"
},
"data533": {
"number": 55,
"name": "Abstützung vorne - zulässige vertikale Beinkraft (P1.Q2)",
"format": 0,
"digit": 0,
"unit": 10,
"category": 0,
"min": 0,
"max": 1000000,
"value": 0,
"hexvalue": "0x00000000",
"binvalue": "0b00000000000000000000000000000000"
.
.
.
.
.
我的问题是我需要在 C# 中设置对象 DataXXX。 我正在尝试:
var dataconfig = JsonConvert.DeserializeObject<Data>(jsonfile);
class 数据在哪里
public class Data
{
public int number { get; set; }
public string name { get; set; }
public int format { get; set; }
public int digit { get; set; }
public int unit { get; set; }
public int category { get; set; }
public int min { get; set; }
public int max { get; set; }
public int value { get; set; }
public string hexvalue { get; set; }
public string binvalue { get; set; }
}
但是我的 dataXXX 在另一个名为 Data 的 object 中,因此代码不起作用。 它也不是一个列表。
在 Newtonsoft.Json 中,有两个 API,一个高级( JsonConvert
)和一个低级(Linq-to-Json)。 如果数据与您拥有的 C# class 结构匹配, JsonConvert
非常适合解析。 Linq-to-Json 非常适合自定义处理和灵活性。
在您的情况下,由于您的属性名称中有数字,您需要对其进行标准化以匹配 C# 类,您可能需要使用 Linq-to-Json。 这会将 JSON 解析为类似于字典的对象。 这是介绍文档。
你应该使用字典
public class Data {
public Dictionary<string,DataModel> data {get; set;}
}
public class DataModel {
public int number { get; set; }
public string name { get; set; }
public int format { get; set; }
public int digit { get; set; }
public int unit { get; set; }
public int category { get; set; }
public int min { get; set; }
public int max { get; set; }
public int value { get; set; }
public string hexvalue { get; set; }
public string binvalue { get; set; }
}
与 Newtonsoft:
JsonConvert.DeserializeObject<Data>(jsonfile); //jsonfile must be includes data.
与 System.Text.Json
JsonSerializer.Deserialize<Data>(jsonfile);
如果只需要数据部分,可以先解析json,之后可以反序列化任意部分
var jsonParsed = JObject.Parse(jsonFile);
Dictionary<string,Data> dataconfig = jsonParsed["data"].ToObject<Dictionary<string,Data>>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.