I have a string in the following format:

{ "Updated" : [ { "FIRST_NAME" : "Aaa", "LAST_NAME" : "Bbb" } ] }

How can I get a dictionary out of this so I can call dict["FIRST_NAME"]?

I've tried the following, but I think they don't work because my string is a JSON array? If that's the case, how do I change it to a regular JSON string? I don't think it needs to be an array with the simple type of data that is in it... The size of the array will never be more than 1 - i.e., there will be no repeating fields.

Dictionary<string, string> dict = serializer.Deserialize<Dictionary<string, string>>(jsonString); //didn't work

JArray jArray = JArray.Parse(jsonString); //didn't work
share|improve this question

You can't (meaningfully) parse a JSON array into a dictionary. – Hot Licks yesterday
1  
But of course, what you have is an object (dictionary) containing a single-element array containing an object (dictionary). Peel the onion. – Hot Licks yesterday
@HotLicks the problem is that I don't know how to do that. Could you help? – TheBeatlemaniac yesterday
1  
Peel the onion. From the initial parse you get a dictionary. Ask for the "Updated" element of that, which will be an array. Ask for the zeroth element of the array, which will be a dictionary. Ask for your target values in that dictionary. – Hot Licks yesterday
feedback

3 Answers

up vote 2 down vote accepted

What you are having is a complex object, which can be parsed as a Dictionary of an Array of a Dictionary!

So you can parse it like:

var dic = serializer.Deserialize<Dictionary<string, Dictionary<string, string>[]>>(jsonString)["Updated"][0];
var firstName = dic["FIRST_NAME"];
var lastName = dic["LAST_NAME"];
share|improve this answer
feedback

A dictionary is not serialized as array.Also keys in a dictionary must be unique and you will probably get an exception that a key with the same name has already be inserted when you try to run your code, if you have repeating fields in your json.

share|improve this answer
I don't have repeating fields. Even though it is an "array", it always just follows that format - i.e., there is only one set of fields. – TheBeatlemaniac yesterday
Still, a dictionary cant be serialized .. – Bhushan Firake yesterday
Is there a similar type (array, etc?) that I could potentially use here? – TheBeatlemaniac yesterday
feedback

It might be easier to just work with a dynamic variable. See Deserialize JSON into C# dynamic object? for more details.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.