【问题标题】:deserialization of json file to poco object not working将json文件反序列化为poco对象不起作用
【发布时间】:2016-03-17 20:37:30
【问题描述】:

我正在尝试在我的 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 ));
}

我做错了什么?

【问题讨论】:

    标签: c# json json-deserialization javascriptserializer


    【解决方案1】:

    您的 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" }
    

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 1970-01-01
      • 2012-09-18
      • 2015-09-24
      • 2021-12-16
      • 1970-01-01
      相关资源
      最近更新 更多