我正在尝试使用 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/