C# Deserialize Root JSON Unknown Keys

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



C# Deserialize Root JSON Unknown Keys



I have a JSON like this and have to deserialize it:


{
"0": {
"foo_id":"xyz",
"bar_id":"abc",
"book":
"0":
"title":"hello",
"author":"person_x"
,
"1":
"title":"hi",
"author":"person_y"

,
"1":
"foo_id":"xyz",
"bar_id":"abc",
"book":
"0":
"title":"hello",
"author":"person_a"
,
"1":
"title":"bye",
"author":"person_b"

,
"random":"string",
"other":"thing"



Similar to this question, except the answer given doesn't work, because I don't have the luxury of creating a class like this


public class RootObject

public Dictionary<string, Object> Objects get; set;



If I do than the Objects field is null after deserialization.



Both the root object and book object are dynamic.



Any other approaches would be appreciated, Thanks in advance.




1 Answer
1



Because the JSON you have does not contains a RootObject that holds a dictionary, you can deserialize straight into a Dictionary like so:


RootObject


Dictionary



Class:


public class Item

[JsonProperty("foo_id")]
public string FooId get; set;

[JsonProperty("bar_id")]
public string BarId get; set;



Deserialize:


var result = JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);



Result:



result



Update:



Since you have changed the original JSON in your question, the second given JSON can be deserialized as so:



Class:


public class RootObject

[JsonExtensionData]
public Dictionary<string, JToken> Items get; set;

[JsonProperty("random")]
public string Random get; set;

[JsonProperty("other")]
public string Other get; set;



Deserialize:


var result = JsonConvert.DeserializeObject<RootObject>(json);





I still have a RootObject class, which is the one I would like to deserialize, because it has some other data I need. Thanks
– qwerty123
Dec 8 '16 at 0:05





@querty123 it's important to know the whole structure of the complete JSON response in order to deserialize
– Jim
Dec 8 '16 at 5:58






any idea how to setup this json, thanks
– qwerty123
Jan 16 '17 at 18:47






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS