RadarCZ
RadarCZ

Reputation: 59

How to convert JSON string with different value types to C# Dictionary?

So, I want to convert this JSON string:

{
 "Posts" : 
    [
     {
       "Title" : "just a string",
       "Id" : "231"
     }, {
       "Title" : "Another string as title",
       "Id": "41"
     }
    ],
  "anotherKey" : "third string"
}

to C# Dictionary, but this code (using Newtonsoft.Json package; where jsonString is variable storing that JSON string):

Dictionary<string,Array> test1 = JsonConvert.DeserializeObject<Dictionary<string,Array>>(jsonString);
Console.WriteLine(test1.Count);

returns an error:

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll

Additional information: Unable to find a constructor to use for type System.Array. Path 'Posts', line 1, position 10.

Is another way how to convert this string to Dictionary?

Upvotes: 1

Views: 1783

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131364

The second entry isn't an array, it's a single string.

Try deserializing to Dictionary<string,object> or Dictionary<string,dynamic> to read all values.

Upvotes: 3

Related Questions