I am using c# interacting with Firebase via the provided REST api.
When I send a GET request to a node, I get the children as expected.
{
"49d360b0-b3a8-4240-bd69-1f91b07365fd" : {
"id" : "49d360b0-b3a8-4240-bd69-1f91b07365fd",
"name" : "Foo",
"value" : "Love me some foo"
},
"8b87b4df-9c04-480b-bb53-43e22059ccfa" : {
"id" : "8b87b4df-9c04-480b-bb53-43e22059ccfa",
"name" : "Bar",
"value" : "Yay, bar"
},
"966fe014-08c3-4f64-93a3-7bd8ed396177" : {
"id" : "966fe014-08c3-4f64-93a3-7bd8ed396177",
"name" : "Name",
"value" : "Text"
}
}
There can be any number of children. I won't know how many until after I get the response. I am trying to get this deserialized into a List, though any kind of IEnumerable should be fine, since that can be converted to a list easily. My Entry class looks like this:
public class Entry
{
public string id { get; set; }
public string name { get; set; }
public string value { get; set; }
}
How do I do the deserialization? I have been using Newtonsoft for most of my JSON handling, will I need to use a different library?
UPDATE: the names of the objects in the JSON are also unknown before making the call, so solutions involving getting values by index won't be super helpful
Here you go (a bit ugly):
public class Item
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
and deserializing code:
dynamic data = JsonConvert.DeserializeObject<dynamic>(jsonString);
var list = new List<Item>();
foreach (var itemDynamic in data)
{
list.Add(JsonConvert.DeserializeObject<Item>(((JProperty)itemDynamic).Value.ToString()));
}
I skip that Guid Id's in original json - do you need them? I will update my answer.
EDIT:
A bit shorter Linq version:
dynamic data = JsonConvert.DeserializeObject<dynamic>(jsonString);
var shorter = ((IDictionary<string, JToken>)data).Select(k =>
JsonConvert.DeserializeObject<Item>(k.Value.ToString())).ToList();
You could also deseriealize the result to a Dictionary like this:
Dictionary<string, Entry> entryDict = JsonConvert.DeserializeObject<Dictionary<string, Entry>>(jsonString);
and then if you want a list of Entries:
List<Entry> entries = entryDict.Select(x => x.Value).ToList();
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