0

I'm having to process 3rd party json data. I'm trying to use JSON.Net, but I'm struggling a little as, in the data, the same type is given a different name every time. See example below.

{
   "success":"1",
   "return":{
      "Mike":{
         "name":"Mike",
         "age":"21",
         "hobbies":[
            {
               "name":"sailing"
            },
            {
               "name":"volleyball"
            }
         ]
      }
   }
}

Here you can see that - in this made up example to illustrate the situation - basically a person object is returned, but it is called "Mike" not person. The next might be called "Sheryl", etc. I would like to just deserialise the whole thing in one go using: var deserialized = JsonConvert.DeserializeObject(jsonString);

However I'm not sure how to build x as it can vary.

I've looked at JsonConverter, but I can't see how that would help in this situation.

Any guidance is much appreciated.

2
  • Consider: [JsonProperty("return")] Dictionary<string, PersonInfo> Result { get; set; } (the Keys in the dictionary will represent the "Mike" or "Sheryl"). However, I suspect that the server is just returning less-than-ideal information, it should likely be a List (the name is already present in the information), not a Dictionary :| Commented Feb 8, 2014 at 20:42
  • Thanks for the suggestion @user2864740. I'll look into that too. I've gone with L.B's answer for the minute as it works great. Thanks once again though. Commented Feb 8, 2014 at 21:36

1 Answer 1

3

Use Dictionary<string,Person> for property Return

var obj = JsonConvert.DeserializeObject<YourObject>(json);

public class Hobby
{
    public string Name { get; set; }
}

public class Person
{
    public string Name { get; set; }
    public string Age { get; set; }
    public List<Hobby> Hobbies { get; set; }
}


public class YourObject
{
    public string Success { get; set; }
    public Dictionary<string,Person>  Return { get; set; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Wow! Just that simple. Let me quickly try it out. Thanks for the quick response by the way - that's excellent.
Oh my god! That totally works. Why have I been beating myself up for the last several days over this. Thank you so much.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.