我有这个简单的 JSON
{
"persons": [{
"firstname": "Brad",
"lastname": "Pitt"
}, {
"firstname": "George",
"lastname": "Clooney"
}, {
"firstname": "Matt",
"lastname": "Damon"
}]
}
这是我在 C# 中的类(class):
public class PersonObject
{
[JsonProperty(PropertyName = "persons")]
public List<Person> Persons { get; set; }
}
public class Person
{
[JsonProperty(PropertyName = "firstname")]
public string Firstname { get; set; }
[JsonProperty(PropertyName = "lastname")]
public string Lastname { get; set; }
}
出于某种原因,它总是返回 null...我真的看不出这有什么问题...使用 JsonConvert.DeserializeObject
没什么问题,因为它适用于其他 JSON 字符串。
_PersonsList = JsonConvert.DeserializeObject<List<PersonObject>>(data);
最佳答案
您的数据不包含 List<PersonObject>
- 它包含一个单个 PersonObject
其中又包含一个 List<Person>
.所以这很好用:
var json = File.ReadAllText("test.json");
var obj = JsonConvert.DeserializeObject<PersonObject>(json);
Console.WriteLine(obj.Persons[0].Firstname); // Prints Brad
使用您当前的代码,您不应该返回一个空引用 - 您应该得到一个异常,如下所示:
Unhandled Exception: Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[PersonObject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
如果您看到一个空引用,这表明您在某处吞下了异常,这值得单独修复。
关于c# - JSON 有效,但代码中的结果返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39508092/