简体   繁体   中英

Deserializing json array with JSON .net

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 (eg [1,2,3]) to deserialize correctly.

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

    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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM