John Dougherty
John Dougherty

Reputation: 131

Derserialize JSON Object from Firebase in C#

I am querying Firebase and retrieve a collection of objects like so:

{"-K5f0ccEKkVkxTAavQKY": {
  "Appeal": {
    "ID": "1450273330435",
    "comps": [
      162248,
      162272,
      162273,
      162281,
      162544
    ],
    "property": {
      "Address": "15 Main Street",
      "propID": 169729
    },
    "timeDateStamp": "Wed Dec 16 2015 08:42:10 GMT-0500 (Eastern Standard Time)",
    "userUUID": "google:229139952703238437512",
    "year": 2016
  }
}}

I would like to deserialize them into objects with this definition:

public class Appeal
{
    public string ID;
    public List<string> comps;
    public AppealProperty property;
    public string timeDateStamp;
    public string UUID;
    public int year;
}

public class AppealProperty
{
    public string address;
    public string propID;
}

I have troubles getting it deserialized. I don't need the initial string (e.g. "K5f0ccEKkVkxTAavQKY"). I'm able to change the object definitions if need be. I have a feeling a Dictionary would be useful.

Upvotes: 6

Views: 4770

Answers (3)

Christophe Chenel
Christophe Chenel

Reputation: 1921

Since I've never been able to parse a DataSnapshot with newtonSoft Json parser, I did this to build a list of object I needed to put in a ListView:

MyModelObject class

    public class MyModelObject: Java.Lang.Object
{
    public string Title { get; set; }
    public string Description { get; set; }

    public MyModelObject(){}
}

into My Listener

        public void OnDataChange(DataSnapshot snapshot)
    {
        List<MyModelObjecct> myList = new List<MyModelObject>();
        myList = databaseService
            .GetMyModelObjectList(snapshot
            .Children?
            .ToEnumerable<DataSnapshot>());
    }

Method into the DatabaseService class

        public List<MyModelObject> GetMyModelObjectList(IEnumerable<DataSnapshot> enumerableSnapshot)
    {
        List<MyModelObject> list = new List<MyModelObject>();

        foreach (var item in enumerableSnapshot)
        {
            list.Add(ObjectExtensions.DataSnapshotToObject<MyModelObject>(item.Children?.ToEnumerable<DataSnapshot>()));
        }

        return list;
    }

ObjectExtensions class

      public static class ObjectExtensions
      {
        public static T DataSnapshotToObject<T>(IEnumerable<DataSnapshot> source)
        where T : class, new()
        {
        var someObject = new T();
        var someObjectType = someObject.GetType();

        foreach (var item in source)
        {
            someObjectType
                     .GetProperty(item.Key)
                     .SetValue(someObject, item.Value.ToString(), null);
        }

        return someObject;
    }
}

Upvotes: 0

Berin Loritsch
Berin Loritsch

Reputation: 11463

The quick and dirty object is to use Dictionary<string,Appeal> as your deserialization target. At that point it would be as simple as:

var firebaseLookup = JsonConvert.DeserializeObject<Dictionary<string,Appeal>>(json);
var data = firebaseLookup.Values.ToList(); // or FirstOrDefault();

This approach would also handle the case if you ever had to get multiple objects at once, and it would give you the opportunity to use that key if it turns out the key was important after all.

Upvotes: 7

Alex
Alex

Reputation: 21766

You could serialise your data into the classes below.

public class AppealProperty
{
    public string Address { get; set; }
    public int propID { get; set; }
}

public class Appeal
{
    public string ID { get; set; }
    public List<int> comps { get; set; }
    public AppealProperty property { get; set; }
    public string timeDateStamp { get; set; }
    public string userUUID { get; set; }
    public int year { get; set; }
}


public class FireBase
{
    public Appeal Appeal { get; set; }
}

public class RootObject
{
    [JsonProperty(PropertyName = " - K5f0ccEKkVkxTAavQKY")]
    public FireBase FireBaseRoot
    {
        get;
        set;
    }
}

Assuming that you are using JSON.NET, you can then get the object you are after, using this snippet:

var firebaseObject = JsonConvert.DeserializeObject<RootObject>(json);
var data = firebaseObject.FireBaseRoot.Appeal;

If the root name is dynamic, as indicated by your comment, you could skip the root instead and serialise straight into the FireBase class:

JObject parsedJson = JObject.Parse(json);
var fireBase = parsedJson.First.Children().First().ToObject(typeof (FireBase));

Upvotes: 5

Related Questions