Aldridge1991
Aldridge1991

Reputation: 1367

c# FIREBASE deserialize

I have a windows form application where I want to deserialize the following Firebase response. It looks as follows:

{
   "Mails":
   {
       "A0":
       {"ID":"[email protected]","Status":false},

       "A1":
       {"ID":"[email protected]","Status":true}
   }
}

I'm using this:

public class Mail
{
    public string ID { get; set; }
    public bool Status { get; set; }
}

//This is the root object, it's going to hold a collection of the mail
public class MailCollection
{
    public List<Mail> Mails { get; set; }
}

public Boolean checkValidLicense(string usermail)
{
    Boolean validUser = false;

    HttpWebRequest req = WebRequest.Create("https://popping-heat-1908.firebaseio.com/.json") as HttpWebRequest;
    using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
    {

        StreamReader reader = new StreamReader(resp.GetResponseStream());
        string json = reader.ReadToEnd();

        //we pass a type parameter telling it what type to deserialize to
        MailCollection result = Newtonsoft.Json.JsonConvert.DeserializeObject<MailCollection>(json);
        foreach (var item in result.Mails)
        {
            if (usermail == item.ID && item.Status) 
            {
                validUser = true;
                break;
             }
        }

        return validUser;
}

I'm getting tones of errors..i'm a bit frustrated right now..do you have any idea?

Upvotes: 2

Views: 928

Answers (2)

MahmutKarali
MahmutKarali

Reputation: 365

You can use it as follows.

    public static UserModel GetUserById(string id)
    {
        var client = new FireSharp.FirebaseClient(firebase.config);
        var get = client.Get(@"User/");

        var deser = JsonConvert.DeserializeObject<Dictionary<string, UserModel>>(get.Body);
        List<UserModel> list = new List<UserModel>();

        foreach (var item in deser)
        {
            list.Add(item.Value);
        }

        return list.Where(q => q.Id.Equals(id)).FirstOrDefault();
    }

Upvotes: 0

Steven Liekens
Steven Liekens

Reputation: 14113

The JSON looks more like a dictionary than a list of strongly typed objects. Try deserializing as Dictionary<string, Mail> instead.

public class MailCollection
{
    public Dictionary<string, Mail> Mails { get; set; }
}

Upvotes: 3

Related Questions