0

I have a Json service I cannot alter as it is not mine. Their Json is a formatted in a way that parsing it is difficult. It looks something like this.

"people": {
     "Joe Bob": {
              "name": "Joe Bob",
              "id": "12345"
     },
     "Bob Smith": {
              "name": "Bob Smith",
              "id": "54321"
     }
 },

I would really prefer this was laid out like a JSon array, however it presently is not. I am wondering the best approach here. Should I alter the Json to look like an array before I parse it or load up the ExtensionData and parse it from that?

There are other items in the feed that I do not have issue with. Just stuck with this one section.

Thanks

vSteve
  • 63
  • 1
  • 1
  • 8
  • mabye this: http://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection.aspx can help? (if you wanted to loop on the items..) – Nadav Ben-Gal Apr 02 '13 at 21:46
  • What are you trying to do with it? Deserialize it into a type? Just loop through each key? What exact problem are you running into? – Mike Christensen Apr 02 '13 at 21:46
  • I would like to create a List with the class containing the name and id. Problem is they named the classes so that is tripping me up. – vSteve Apr 02 '13 at 21:49

1 Answers1

0

You can use json.net to deserialize the data (the json you pasted, and doing only one parsing, without modifying anything).

using dynamic foo = JsonConvert.DeserializeObject<dynamic>(data) than, you can iterate the list using foo.people, accessing the Name and Value.

you can create a class (if you know what the schema is, and to deserialize the data into a list of the given class such as:

    public class People
    {
        [JsonProperty(PropertyName="people")]
        public IDictionary<string, Person> Persons { get; set; }
    }

    public class Person
    {
        [JsonProperty(PropertyName="name")]
        public string Name { get; set; }

        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }
    }

and than call:

var obj = JsonConvert.DeserializeObject<People>(data);
foreach (var item in obj.Persons.Values)
{
      //item is instance of Person      
}

Another good and possible option will be: How can I navigate any JSON tree in c#?

Community
  • 1
  • 1
Nadav Ben-Gal
  • 549
  • 3
  • 13
  • This does work with json.net. It does not with the standard Microsoft stuff. Thanks for the assistance. – vSteve Apr 03 '13 at 01:19