简体   繁体   中英

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?

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.

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