2

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
Kalina
  • 5,504
  • 16
  • 64
  • 101
  • You can't (meaningfully) parse a JSON array into a dictionary. – Hot Licks Jan 14 '13 at 19:24
  • 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 Jan 14 '13 at 19:25
  • @HotLicks the problem is that I don't know how to do that. Could you help? – Kalina Jan 14 '13 at 19:28
  • 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 Jan 14 '13 at 20:20

2 Answers2

2

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"];
Kamyar Nazeri
  • 25,786
  • 15
  • 50
  • 87
0

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

Community
  • 1
  • 1
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73