繁体   English   中英

将 json 文件反序列化为 poco 对象不起作用

[英]deserialization of json file to poco object not working

我正在尝试在我的 VS 项目中用 .json 文件中的数据实例化一个 poco 对象。 当我使用此代码时,它只返回一个空对象。

班级:

public class Person
{
    public int id { get; set; }
    public string name { get; set; }
}

文件中的 Json 文本:

{
    "person": 
    {
        "id": 1,
        "name": "joe"
    }
}

Program.cs 中的代码:

static void Main(string[] args)
{
    string jspath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Json\json1.json");

    //person object results in 0 for id and null for name (empty)
    Person person = new JavaScriptSerializer().Deserialize<Person>(File.ReadAllText(jspath ));
}

我究竟做错了什么?

您的 JSON 文件不正确。

它应该是:

{ "id": 1, "name": "joe" }

证明:

Person p = new Person
{
    id = 1,
    name = "joe"
};
var sb = new StringBuilder();
new JavaScriptSerializer().Serialize(p, sb);
Console.WriteLine(sb.ToString()); // Outputs: { "id": 1, "name": "joe" }

暂无
暂无

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

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