I'm call an API that returns the following json
{
"services":{
"Home":{
"Homecall":{
"id":"10"
},
"Two Day":{
"id":"11"
},
"Three Day":{
"id":"12"
}
}
}
}
What would be the best possible way to parse this so it returns 'Home' as a unqiue variable, "homecall","Two day" and "three day" along with their ID in c#?
CodePudding user response:
you can try something like this
HomeClass home = new HomeClass
{
Home = ((JObject)JObject.Parse(json)["services"]["Home"]).Properties()
.Select(h => new MyClass { Name = h.Name, Id = Convert.ToInt64(h.Value["id"]) })
.ToList()
};
public class HomeClass
{
public List<MyClass> Home { get; set; }
}
public class MyClass
{
public long Id { get; set; }
public string Name { get; set; }
}
output in a json format
{
"Home": [
{
"Id": 10,
"Name": "Homecall"
},
{
"Id": 11,
"Name": "Two Day"
},
{
"Id": 12,
"Name": "Three Day"
}
]
}