简体   繁体   中英

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.

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;

Valid json for Test class is below

{ "Name": { "id": 10, "name": "Name", "revisionDate": 1390293827000 } }

and Also your json is in containg more data then only test class so you can also use like

Dictionary<string,Test> dictionary= JsonConvert.DeserializeObject<Dictionary<string,Test>>(json);

Test oputput=dictionary["Name"];  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM