Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.NET deserializing object returns null

I would like to deserialize a string o JSON and output data on a string:

public class Test
{
    public int id { get; set; }
    public string name { get; set; }
    public long revisionDate { get; set; }
}

private void btnRetrieve_Click(object sender, EventArgs e)
{
    string json = @"{""Name"":{""id"":10,""name"":""Name"",""revisionDate"":1390293827000}}";
    var output = JsonConvert.DeserializeObject<Test>(json);
    lblOutput.Text = output.name;
}

This is intended to output the name property of the string json. However, it returns nothing.

like image 279
jacobz Avatar asked Jan 22 '14 11:01

jacobz


1 Answers

The JSON you posted can be deserialized into an object which has a Name propery of type Test, not into a Test instance.

This

string json = @"{""id"":10,""name"":""Name"",""revisionDate"":1390293827000}";

would be a representation of a Test instance.

Your JSON may be deserialized into something like this:

public class Test
{
   public int id { get; set; }
   public string name { get; set; }
   public long revisionDate { get; set; }
}

public class Foo
{
    public Test Name { get; set; }
}

// ...


var output = JsonConvert.DeserializeObject<Foo>(json);
lblOutput.Text = output.Name.name;
like image 91
Mauro Cerutti Avatar answered Sep 29 '22 07:09

Mauro Cerutti