Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Deserialization in C# comparison

Tags:

json

c#

linq

I have never worked before with JSON data. I'm trying to deserialize the following line:

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

I'm using the following code but it's not working:

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();

        dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

        foreach (var item in result.Mails)
        {
            if (usermail == item.ID && item.Status == "true") 
            {
                validUser = true;
                break;
             }

        }

        return validUser;
    }

I'm getting:

'Newtonsoft.Json.Linq.JValue' does not contain a definition for 'ID'.

like image 652
Aldridge1991 Avatar asked Dec 10 '25 05:12

Aldridge1991


1 Answers

Do not deserialize to dynamic type unless you have a strong reason to do so. Instead, create a type to deserialize to. A great tool for that is json2csharp, though you may often need to make minor adjustments for things it can't infer. Below, we've made two classes. Mail represents the individual items, and MailCollection is the root JSON object we're deserializing from, which simply contains a collection of Mail objects.

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; }
}

//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) //since item.Status is a bool, don't compare to a string.
    {
        validUser = true;
        break;
    }
}
like image 148
mason Avatar answered Dec 11 '25 19:12

mason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!