Reputation: 7724
I have a json string that looks like this:
{
"documents": [
{
"name": "20200809/1",
"fields": {
"details": {
"stringValue": "bad"
},
"paid": {
"stringValue": "yes"
}
}
},
{
"name": "20200809/4",
"fields": {
"details": {
"stringValue": "good"
},
"paid": {
"stringValue": "no"
}
}
}
]
}
the strings that matter for me are name
, details
and paid
. When I retrieve the information from the server, it comes like this json.
I'm using JSON .net (JsonConvert
) to deserialize but I think I'm doing it wrong. How can I get name
and details
from this json?
List<object> json = JsonConvert.DeserializeObject<List<object>>(jsonString);
Dictionary<string, object> dict = json[0] as Dictionary<string, object>;
//get name
string name = dict["name"] as string;
It gives me:
Cannot deserialize the current JSON object because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Upvotes: 0
Views: 89
Reputation: 152
string jsonString = "{'documents':[{'name':'20200809/1','fields':{'details':{'stringValue':'bad'},'paid':{'stringValue':'yes'}}},{'name':'20200809/4','fields':{'details':{'stringValue':'good'},'paid':{'stringValue':'no'}}}]}";
//Note: You must convert to JObject
var jsonObject = JObject.Parse(jsonString);
//Note: And get documents object get zero index and "name" key and fixed!
var jsonMemberName = jsonObject["documents"][0]["name"].ToString();
Upvotes: 1
Reputation: 438
The complete object represented by your JSON is a Dictionary<string, List<Dictionary>>
- you will have to parse the whole structure and use a map/collect loop to get the specific keys that you need, or can use JSON Path
Upvotes: 1