问题
I am using third-party API, so I cannot change the response structure. In response I am getting something like this:
{
"Code": "SomeCode",
"Name": "Some Name",
"IsActive": true,
"Prop13": {
"LongId": "12",
"ShortId": "45"
},
"Prop26": {
"LongId": "12",
"ShortId": "45"
},
"Prop756": {
"LongId": "12",
"ShortId": "45"
}
}
I need to parse it to next type of class:
public class Class1
{
public string Code { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public Dictionary<string, PropertiesClass> Properties { get; set; }
}
public class PropertiesClass
{
public int LongId { get; set; }
public int ShortId { get; set; }
}
Properties "Prop13", "Prop26" etc are dynamic in response, there could none of them, or with completely other name. So I must store only Code, Name and IsActive (this are always present) to class properties, all other should go to the Dictionary. And the name of the property should be stored as a key in the dictionary.
I cannot find anything that can help me in https://www.newtonsoft.com/json/help/html/Introduction.htm
回答1:
There's one way I can think of.
Your Class1
needs a slight modification:
public class Class1
{
public string Code { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
[JsonExtensionData]
public Dictionary<string, JToken> _JTokenProperty { get; set; }
public Dictionary<string, PropertiesClass> Properties1 { get; set; } = new Dictionary<string, PropertiesClass>();
}
Then where you parse the object, you want to pare it like so:
var obj = JsonConvert.DeserializeObject<Class1>("{\"Code\":\"SomeCode\",\"Name\":\"Some Name\",\"IsActive\":true,\"Prop13\":{\"LongId\":\"12\",\"ShortId\":\"45\"},\"Prop26\":{\"LongId\":\"12\",\"ShortId\":\"45\"},\"Prop756\":{\"LongId\":\"12\",\"ShortId\":\"45\"}}");
foreach(KeyValuePair<string, JToken> token in obj._JTokenProperty)
{
obj.Properties1.Add(token.Key, token.Value.ToObject<PropertiesClass>());
}
This will generate the desired output.
Edit: Thanks to @Nkosi for the link and suggestion to keep it self-contained.
You would add the following to Class1
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
foreach (KeyValuePair<string, JToken> token in _JTokenProperty)
{
Properties1.Add(token.Key, token.Value.ToObject<PropertiesClass>());
}
}
And your de-serialization just becomes:
var obj = JsonConvert.DeserializeObject<Class1>("{\"Code\":\"SomeCode\",\"Name\":\"Some Name\",\"IsActive\":true,\"Prop13\":{\"LongId\":\"12\",\"ShortId\":\"45\"},\"Prop26\":{\"LongId\":\"12\",\"ShortId\":\"45\"},\"Prop756\":{\"LongId\":\"12\",\"ShortId\":\"45\"}}");
来源:https://stackoverflow.com/questions/53279441/how-to-parse-not-fully-corresponding-json