0

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.

5
  • an array starts with [and an object starts with { - guess what you have here Commented Aug 9, 2020 at 6:31
  • 2
    You can read the docs for JSON Path Commented Aug 9, 2020 at 6:35
  • 1
    So the beginning object is a Dictionary<string, List<object>> instead? Commented Aug 9, 2020 at 6:36
  • Somehow ... but that would not be very helpful. Try it to "feel" what is bad about it. If you do not want to build a class structure for that json then use JSON Path Commented Aug 9, 2020 at 6:39
  • Feel free to post the use of JObject as answer and I'll gladly accept it. Just solved the problem using it :) Thanks. Commented Aug 9, 2020 at 6:45

2 Answers 2

1
    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();
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.