Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize response from firebase

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

like image 592
Erin Aarested Avatar asked Jul 24 '14 17:07

Erin Aarested


2 Answers

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();
like image 108
Ilya Luzyanin Avatar answered Oct 03 '22 09:10

Ilya Luzyanin


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();
like image 21
Edminsson Avatar answered Oct 03 '22 11:10

Edminsson