6

I have JSON like this:

{
   "Property":"Blah blah",
   "Dictionary": {
        "Key1" : "Value1",
        "Key2" : "Value2",
        "Key3" : "Value3"
   }
}

I want to extract the "Dictionary" object as a Dictionary (so it'd be like Key1 => Value1, etc.). If I just had the "Dictionary" object directly, I could use:

 JsonConvert.DeserializeObject<Dictionary<string, string>>

What's the best way to get just the Dictionary property as a Dictionary?

Thanks in advance! Tim

4 Answers 4

10

Took me a little while to figure out, but I just didn't feel great about using string parsing or regexes to get at the inner JSON that I want.

Simple enough; I did something along these lines to get at the inner data:

var jObj = JObject.Parse(jsonText);
var innerJObj = JObject.FromObject(jObj["Dictionary"]);

Works well enough.

Sign up to request clarification or add additional context in comments.

1 Comment

How do you go from innerJObj (type JObject) to a Dictionary?
1

I think you'd have to parse the JSON and remove the outer object. You can dictate what kind of object you are deserializing to, but there is no way to tell it NOT to deserialize the outermost object.

1 Comment

Thoughts on the best way to get at the inner JSON? String parsing/regex, or is there some JSON.NET-provided method?
1

You could also define the property as Dictionary in a class.

 var str = @"{
   ""Property"":""Blah blah"",
   ""Dictionary"": {
       ""Key1"" : ""Value1"",
       ""Key2"" : ""Value2"",
       ""Key3"" : ""Value3""
   }
 }";

 class MyObject {
   string Property { get; set; }
   Dictionary<string, string> Dictionary { get; set; }
 }

 MyObject obj = JsonConvert.DeserializeObject<MyObject>(str);
 var dict = obj.Dictionary;

1 Comment

You don't have to add the "Property"-property if you don't want to use it. This speeds up the software if you're working with big Json-objects.
0

For reference, your answer is to (de)serialize json fragments. Also answered here, but your solution looks more succinct. Curious about performance differences...

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.