1

I'm having an issue with JSON that I'm getting back for a hotel booking API. Essentially I'm taking the output and trying to create a class so that I can put it into an object. The problem is this: The JSON is returning objects and we can't readily use this format to make a C# class because of how it's formatted:

Example of how the JSON is formatted

Here is a snippet of it. Attributes is the highest level, then "pets" is next. The values we need for this are id: 5058 and name: Service Animals are allowed, however they are creating this "5058" and "5059" and "2050" object which is making it difficult to create a class and properly deserialize it.

I'm fairly new at C# (formerly long-time C programmer), so trying to understand the best way to make a class for something like this where the "5058" is not actually created as a class ... I would prefer if we could ingest that level into an array or list perhaps?

This is what something like json2csharp.com outputs...

public class Pets
{
    public _5058 _5058 { get; set; }
    public _5059 _5059 { get; set; }
    public _2050 _2050 { get; set; }
} 

And then

public class _5059
{
    public string id { get; set; }
    public string name { get; set; }
}

5059 should not be a class... That appears to be the name of the object; I want to ignore that because the ID: in the object is 5059

This wont work since there are thousands of IDs, and we're not looking to create a separate class for each ID -

I would like to make a class more like this

public class Pets
{
   public string id { get; set; } 
   public string name {get; set; }
}

This is how I'm receiving the JSON

{
   "pets":{
      "5058":{
         "id":"5058",
         "name":"Service animals are allowed"
      },
      "5059":{
         "id":"5059",
         "name":"Service animals are exempt from fees/restrictions"
      },
      ...
   }
}

(This is a small snippet)

Again, here, they have "5059":{"id":"5059","name":"Service animals...."

So, what's the best way to ingest this with a class in C# without creating classes for the ID, the way a JSON to C# class creator would do?

Thanks for you help

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

2

That looks like a Dictionary<string, Pet> where those 5058, 5059, etc. are the keys.

public class Data
{
    public Dictionary<string, Pet> pets { get; set; }
}

public class Pet
{
    public string id { get; set; }

    public string name { get; set; }
}

Deserialize the json as below

var data = JsonSerializer.Deserialize<Data>(json);

or if you're using Newtonsoft.Json

var data = JsonConvert.DeserializeObject<Data>(json);
pfx
  • 20,323
  • 43
  • 37
  • 57