I have a JSON string with some key is dynamic.
{
"status": {
"code": "200",
"message": "OK"
},
"total": 1,
"results": [
{
"leader": "00689cam a2200217 a 4500",
"fields": [
{
"020": {
"ind2": "#",
"ind1": "#",
"subfields": [
{
"a": "9786041092587"
},
{
"c": "200000đ"
}
]
}
},
{
"041": {
"ind2": "#",
"ind1": "0",
"subfields": [
{
"a": "vie"
}
]
}
}
]
}
]}
In there, "020", "041", "a", "c" are dynamic keys.
I am trying to deserialize it into a C# object model:
[DataContract]
public class Data
{
[DataMember]
public Status status { get; set; }
[DataMember]
public int total { get; set; }
[DataMember]
public List<Result> Results { get; set; }
}
[DataContract]
public class Status
{
[DataMember]
public string code { get; set; }
[DataMember]
public string message { get; set; }
}
[DataContract]
public class Result
{
[DataMember]
public string leader { get; set; }
[DataMember]
public List<Field> fields { get; set; }
}
[DataContract]
public class Field
{
[DataMember]
List<Tag> Tags { get; set; }
}
[DataContract]
public class Tag
{
[DataMember]
public string ind1 { get; set; }
[DataMember]
public string ind2 { get; set; }
[DataMember]
public List<subField> subfields { get; set; }
}
[DataContract]
public class subField
{
[DataMember]
public List<sCode> Codes { get; set; }
}
[DataContract]
public class sCode
{
[DataMember]
public string key { get; set; }
[DataMember]
public string value { get; set; }
}
I am deserializing the JSON format with the code below:
string strJson = f["dataJson"].ToString();
var deserializedData = JsonConvert.DeserializeObject<Dictionary<string, Data>>(strJson);
I am sure that I’m wrong something here but I can’t find them. Any help would be really appreciated! Thanks so much!
2
Answers
You’re trying to deserialise into a dictionary. Changing the type to deserialise into to your
Data
type seems to work fine.https://dotnetfiddle.net/iq8qMa
I’m assuming that
f["dataJson"].ToString()
returns the JSON string that you posted above.Pls try my codes below.
And here’s my test result.