Cate Borisova
Cate Borisova

Reputation: 13

Parse a Json File - JsonConvert

I have JSON file like:

[
  12,
  [
    {
      "id": "131",
      "name": "Cate"
    },
        {
      "id": "132",
      "name": "Mike"
    }
  ],
  "Result OK"
]

And Code:

        private static void Main(string[] args)
        {
                using (var r = new StreamReader(@"C:\Path\data1.json"))
                {
                    var json = r.ReadToEnd();
                    try
                    {
                        var items = JsonConvert.DeserializeObject<JsonBody>(json);
                        Console.WriteLine(items);
                    }
                    catch (JsonSerializationException ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
        }
        public class JsonBody
        {
            public int someint;
            public List<Dictionary<string, Item>> item;
            public string somestring;

        }
        public class Item
        {
            [JsonProperty("id")] public string id;
            [JsonProperty("name")] public string name;
        }

Error:Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Json_parser.Parse2+JsonBody' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

What should be rewritten in the code to avoid this error. How do I parse this JSON correctly? I need to get all items from the Item class.

Upvotes: 1

Views: 101

Answers (2)

Ragou
Ragou

Reputation: 1

At first sight the problem come from the model we are using for the deserialization.

Try this one instead, in which the dictionary is replace by just your model Item :

        public class JsonBody
        {
            public int someint;
            public List<Item> item;
            public string somestring;

        }

As mentionned by @Lasse V. Karlsen it need to be deserialized into a list of JsonBody, so you have to alter this line of code as well:

var items = JsonConvert.DeserializeObject<List<JsonBody>>(json);

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391496

Since the root of your JSON document is a list, you need to deserialize it into a collection type in C# using Json.Net. Unfortunately, this kind of data structure with mixed element types is a bit hard to consume.

If you know 100% that the root of the document will always be an array, you can deserialize it like this:

JArray root = JArray.Parse(json);

Then, if you know 100% that the 2nd element of this array will be the nested array of items you're interested in you can use this:

Item[] items = root[1].ToObject<Item[]>();

So your method could be simplified to:

string json = File.ReadAllText(@"C:\Path\data1.json");
JArray root = JArray.Parse(json);
Item[] items = root[1].ToObject<Item[]>();

However, if you need to hunt for the nested array, in that it will not always be the 2nd element, you can use this:

string json = File.ReadAllText(@"C:\Path\data1.json");
JArray root = JArray.Parse(json);
foreach (var element in root)
    if (element is JArray)
    {
        Item[] items = element.ToObject<Item[]>();
        // ...
    }

Upvotes: 1

Related Questions