c# - json 文件反序列化为 poco 对象不起作用

标签 c# json json-deserialization javascriptserializer

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

类(class):

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

关于c# - json 文件反序列化为 poco 对象不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36071222/

相关文章:

C# if 函数 : get operator from Text file

c# - 如何告诉 Blazor Webassembly 网站的访问者他们的浏览器不支持 Webassembly?

c# - Razor 语法/WebMatrix - C#

java - Jackson json反序列化以整数(原始数据)作为POJO的关键

c# - 填充二维矩形

java - 从 android 2.1 使用 ado.net 数据服务

jquery - 使用 jQuery 获取 JSON Facebook Graph API 用户信息

json - 用于按条件对 JSONB 数组的任何元素进行过滤的 WHERE 子句?

java - 使用 Jackson 反序列化字符串以映射多种类型

java - 如何在 Spring Boot 中反序列化/序列化类型 Geometry?