7

How do I convert a JSON array like this

[{"myKey":"myValue"},
{"anotherKey":"anotherValue"}]

to a C# Dictionary with json.net or system classes.

json.net can serialize directly to a dictionary, but only if you feed it an object, not an array.

3

6 Answers 6

10

Maybe converting to array of KeyValuePairs will help

using System.Linq;

var list = JsonConvert.DeserializeObject<IEnumerable<KeyValuePair<string, string>>>(jsonContent);
var dictionary = list.ToDictionary(x => x.Key, x => x.Value);
Sign up to request clarification or add additional context in comments.

3 Comments

Did this actually work for you? I got the correct number of kvps but they had null keys and values. I think it is because Json.Net can't construct them with the Create() method. I ended up having to use a list of single element dictionaries.
This doesn't seem to work. An IEnumerable<KeyValuePair<string, string>> will serialize as [{"Key":"myKey","Value":"myValue"},{"Key":"anotherKey","Value":"anotherValue"}] not [{"myKey":"myValue"},{"anotherKey":"anotherValue"}]. See: dotnetfiddle.net/ChfYuV.
Its incorrect and not working.
6

For anyone interested - this works, too:

Example JSON:

[{"device_id":"VC2","command":6,"command_args":"test args10"}, {"device_id":"VC2","command":3,"command_args":"test args9"}]

C#:

JsonConvert.DeserializeObject<List<JObject>>(json)
            .Select(x => x?.ToObject<Dictionary<string, string>>())
            .ToList()

Comments

5

Its quite simple actually :

lets say you get your json in a string like :

string jsonString = @"[{"myKey":"myValue"},
{"anotherKey":"anotherValue"}]";

then you can deserialize it using JSON.NET as follows:

JArray a = JArray.Parse(jsonString);

// dictionary hold the key-value pairs now
Dictionary<string, string> dict = new Dictionary<string, string>();

foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = (string)p.Value;
        dict.Add(name,value);
    }
}

2 Comments

@user1585345 what do you mean?
my apologies for not reading it right - i have updated the code!
4

I found that using a list of KeyValuePairs didn't work. I got the right number of elements but they had null Keys and Values.

In the end the only solution that worked for me was deserialising to a list of dictionaries (which each had a single kvp element).

Comments

0

The data must to be sent as follows (format):

"Values": [
  {"Key" : "abc"  , "Value": 23.14},
  {"Key" : "abc1" , "Value": 23.11},
  {"Key" : "abc2" , "Value": 23.17},
  {"Key" : "abc3" , "Value": 23.19}
]

thereby, the converting process will work. It worked fine to me in my attempt to convert from JSON to dictionary<string,decimal>

Comments

0

Since you can only deserialize from an object, do just that by manipulating the JSON string a little first. Wrap it in an object:

json = String.Format("{{\"result\":{0}}}", json);

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.