1

I'm trying to deserialize JSON to C# object using NewtonsoftJson.

My json looks like this:

{"something" : [ "key1" : "value1", "key2" : "value2"]}

But it's not a full json. So it should be kind of part of large object. I can't use this solution JSON array to C# Dictionary because I use

JsonConvert.DeserializeObject<MyObject>(json);

Does it possible to initialize object like this?

public class Something
{   
    [JsonProperty]
    public Dictionary<string, string> MyDictionary;
}

But when I'm trying to do that I get exception:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,ConsoleApp4.TxPerfMeasurements]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. 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 that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

Valerii
  • 13
  • 4
  • 1
    That's not valid JSON, you can try it out here https://jsonformatter.curiousconcept.com/ – LLL Apr 01 '20 at 08:18
  • 1
    That is not valid JSON, can you make sure you are not misrepresenting the actual problem here? The problem with the example you've shown is that you can't have an array of key:value type of pairs, that's an object. So it either has to be an array of elements, in which case the colons are not supposed to be there, or it has to be an object, in which case it should use `{...}` and not `[...]`. With the current example data there is no way you can get Json.Net to deserialize this, no matter what types you try to deserialize it into. Please ensure you have the right input example. – Lasse V. Karlsen Apr 01 '20 at 08:19
  • Sorry, I forgot about brakes, actually it looks like this:{"something":[{"key1":"value1"},{"key2":"value2"}]} – Valerii Apr 01 '20 at 08:27

1 Answers1

0

Input

{
  "something": [
    { "key1": "value1" },
    { "key2": "value2" }
  ]
}

Your model should look like below

public class Something
{   
    public List<Dictionary<string, string>> something { get; set; }
}

Use Linq to convert to Dictionary

var result = JsonConvert.DeserializeObject<Something>(json);
var dict = result.something.SelectMany(d => d).ToDictionary(e => e.Key, e => e.Value);

Output

enter image description here

Krishna Varma
  • 4,238
  • 2
  • 10
  • 25