简体   繁体   English

Json.NET反序列化对象返回null

[英]Json.NET deserializing object returns null

I would like to deserialize a string o JSON and output data on a string: 我想反序列化字符串o JSON并输出字符串数据:

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 . 这是为了输出字符串jsonname属性。 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. 您发布的JSON可以反序列化为一个对象,该对象具有Test类型的Name属性,而不是Test实例。

This 这个

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

would be a representation of a Test instance. 将是Test实例的表示。

Your JSON may be deserialized into something like this: 你的JSON可能被反序列化为这样的东西:

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 Test类的有效json如下所示

{ "Name": { "id": 10, "name": "Name", "revisionDate": 1390293827000 } } {“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 而且你的json正在包含更多数据,然后只有测试类,所以你也可以使用like

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

Test oputput=dictionary["Name"];  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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