1

I am trying to convert a JSON array to a C# dictionary. My Box class has "id" and "color" properties.

{
   "boxes" [
       {"id":0, "color":"red"},
       {"id":1, "color":"green"},
       {"id":2, "color":"blue"}
   ]
}

I've tried a few things, but haven't had any luck getting this to work yet.

List<Box> jsonResponse = JsonConvert.DeserializeObject<List<Box>>(File.ReadAllText(filePath));
5
  • Does it work for you if you simply do JsonConvert.DeserializeObject<Dictionary<int, string>>(boxes) ? Commented Jan 27, 2019 at 13:00
  • 2
    This is syntactically invalid. { "boxes": [ .. ] } would be correct. Commented Jan 27, 2019 at 13:00
  • Good point @JeroenMostert, edited. This is a trimmed down version of what I'm using, and I missed that part. Commented Jan 27, 2019 at 13:15
  • @Fabjan "To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. " I've decided to add a function for list -> dictionary. Commented Jan 27, 2019 at 13:19
  • @Idios I've updated my answer according to scenario that you work with Commented Jan 27, 2019 at 13:25

2 Answers 2

1

Well the thing is that your Dictionary is in nested property. And even more - it's not really a dictionary. It is an array of objects where each object consists of two fields - id and color (whereas in dictionary we have key-value pairs).

You could deserialize your json into anonymous object with correct structure and then get the array of boxes out of it and convert it to dictionary:

var box = new { id = 0, name = "" };
var jsonObj = new { boxes = new[] { box } };

var dict = JsonConvert.DeserializeAnonymousType(myJson, jsonObj).boxes
                                 .ToDictionary(b => b.id, b => b.name);
Sign up to request clarification or add additional context in comments.

Comments

0

JSON doesn't need {} at the top level - so you can just have your list of items in {}'s surrounded by [].

[
    {"id":0, "color":"red"},
    {"id":1, "color":"green"},
    {"id":2, "color":"blue"}
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.