I'm trying to write an API - the expected output (for a 3rd party) as shown on their website is the JSON below:
{
"api_version" : 4 ,
"hotel_ids" : [97497],
"hotels" :
[
{
"hotel_id": 97497,
"room_types":
{
"Fenway Room":
{
"url": "someurlhere",
"price": 178.50,
"room_code": "SINGLE"
}
}
}
]
}
I'm using the online tool: http://json2csharp.com/
It gives me the following classes:
public class FenwayRoom
{
public string url { get; set; }
public double price { get; set; }
public string room_code { get; set; }
}
public class RoomTypes
{
public FenwayRoom __invalid_name__Fenway Room { get; set; }
}
public class Hotel
{
public int hotel_id { get; set; }
public RoomTypes room_types { get; set; }
}
public class RootObject
{
public int api_version { get; set; }
public List<int> hotel_ids { get; set; }
public List<Hotel> hotels { get; set; }
}
You can see in RoomTypes:
FenwayRoom __invalid_name__Fenway Room { get; set; }
I'm wondering if their spec for the JSON is wrong, or is there a way for me to create the classes to return the JSON they are expecting?
In the example, I believe the room type "Fenway Room" is a variable - so I don't think it can also be a class name. But it may just be that I don't know how to create a class like this.
I just can't figure out the "Fenway Room" - which I think needs to have something like: "Room Name":"Fenway Room" - but maybe there is another way of defining the classes so that it doesn't need a label "Room Name".
I'd appreciate any help in confirming if it is possible to create classes to match against their JSON.
Thanks, Mark
When using Json.NET the output
"room_types":
{
"Fenway Room":
{
"url": "someurlhere",
"price": 178.50,
"room_code": "SINGLE"
}
}
}
look exactly what you would get serializing a Dictionary.
Change your class to
public class Room
{
public string url { get; set; }
public double price { get; set; }
public string room_code { get; set; }
}
public class Hotel
{
public int hotel_id { get; set; }
public Dictionary<string, Room> room_types { get; set; }
}
public class RootObject
{
public int api_version { get; set; }
public List<int> hotel_ids { get; set; }
public List<Hotel> hotels { get; set; }
}
This is all predicated on using Json.NET, which gives you this serialization/deserialization of dictionaries in this format for free. You can do this with the .NET framework serializer, but you need to do extra work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With