I have been working trying to import a list of objects from Json to C#.
The Json structure is:
"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"
.
.
.
.
.
My problem is that I need to set up the objects DataXXX in C#. Im trying with:
var dataconfig = JsonConvert.DeserializeObject<Data>(jsonfile);
Where class Data is
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; }
}
But my dataXXX is inside another object called Data so the code is not working. And it's not a list also.
CodePudding user response:
In Newtonsoft.Json, there are two API's, one high-level (JsonConvert
) and one low-level (Linq-to-Json). JsonConvert
is great for parsing if the data matches the C# class structures you have. Linq-to-Json is great for custom processing and flexibility.
In your case, since your property names have numbers in them that you need to standardize to match C# classes, you probably need to use Linq-to-Json. This parses JSON into objects similar to a Dictionary. Here are the intro docs.
CodePudding user response:
you should use Dictionary
public class Data {
public Dictionary<string,DataModel>()
}
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; }
}
with Newtonsoft:
JsonConvert.DeserializeObject<Data>(jsonfile); //jsonfile must be includes data.
with System.Text.Json
JsonSerializer.Deserialize<Data>(jsonfile);