I have a very strange situation with a customer's JSON. They send an array of objects named as the ID (which is a number) :
Instead of the expected object name allowing for a simple parsing, such as "amenity".
How can we parse this into a List of objects containing ID and Name? Here's the exact JSON text:
"amenities":{ "2194":{ "id":"2194", "name":"Breakfast for 2" }, "2192":{ "id":"2192", "name":"Free WiFi" } }
And there are other case when we have more fields , not only id, and name inside each object
"amenities":{ "2194":{ "id":"2194", "name":"Breakfast for 2", "validto" : "2022-10-30" }, "2192":{ "id":"2192", "name":"Free WiFi", "validto" : "2022-10-30" } }
Thank you all!!!
CodePudding user response:
You need two classes, one to be the main(Class1) where the json will be converted into and another class(Class2) for the object in the array. Then you can convert the dictionary in the main into a List of Class2 values of the dictionary.
public class MyClass1{
public Dictionary<string,MyClass2> amenities;
}
public class MyClass2{
public string id;
public string name;
public string validto;
}
First deserialize into MyClass1, then get the Values from the Dictionary and turn into List.
List<MyClass2> list = JsonConvert.DeserializeObject<MyClass1>(jsonstring).amenities.Values.ToList()