1, Use scenario
When we deserialize the JSON entity set, if the field is fixed, then we can simply serialize the entity set written by the corresponding field. For example:
{
"data":[
{
"houseid": "210166268",
"city": "Tangshan",
"pv": "1"
}
],
"message": "Success"
}
But how do we deal with dynamic JSON data (without fixed fields), such as the following structure: is it silly? Because there is a time node, it is not fixed. Next, we will start to introduce how to deserialize the following format.
//Note that the following time nodes are not fixed, and we cannot correspond to the specified fields
{
"content": {
"20180123": [
{
"houseid": "210166268",
"city": "Tangshan",
"pv": "1"
},
{
"houseid": "210181300",
"city": "Tangshan",
"pv": "1"
}
],
"20180124": [
{
"houseid": "210166268",
"city": "Tangshan",
"pv": "1"
}
]
},
"message": "Success"
}
2, Dynamic entity set deserialization
Need to introduce: Newtonsoft.Json.
Let's say we want to sequence the house ID, city, PV information into a list. The code is as follows:
//Final target format
public class DataModel
{
//Date string
public string DateStr { get; set; }
//Daily information list
public List<EntityModel> EntityList { get; set; }
}
//data model
public class EntityModel
{
public string HouseId { get; set; }
public string City { get; set; }
public string PV { get; set; }
public override string ToString()
{
return HouseId +City +PV;
}
}
2.1 treatment results
2.2 processing logic
//analysis
Newtonsoft.Json.Linq.JObject resultObject = Newtonsoft.Json.Linq.JObject.Parse(resultStr);
//Convert to list (get Content)
List<Newtonsoft.Json.Linq.JToken> listJToken = resultObject["content"].Children().ToList();
//ergodic
foreach (var item in listJToken)
{
//Convert to key value pair format
var temp_item = (Newtonsoft.Json.Linq.JProperty)item;
Console.WriteLine("Name:" + temp_item.Name + "\nValue:" + temp_item.Value );
Console.WriteLine("------------------------------------------------------------------------");
//TODO: you should know the following steps. If you want to get the list < entitymodel > type, you can serialize the value directly.
//var temp_list = JsonConvert.DeserializeObject<List<EntityModel>>(temp_item.Value.ToString());
}