我有一个看起来像这样的 JSON 文件:
{
"foo": "bar",
"pets": {
"dog": {
"name": "spot",
"age": "3"
},
"cat": {
"name": "wendy",
"age": "2"
}
}
}
我想将其反序列化为 C# 类:
public class PetObject
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("age")]
public string Age { get; set; }
}
public class FooObject
{
[JsonProperty("foo")]
public string Foo { get; set; }
[JsonProperty("pets")]
public List<PetObject> Pets { get; set; }
}
使用这样的代码进行转换是行不通的,因为 pets 里面有多个对象,而且不是 JSON 数组。
//does not work
FooObject content = JsonConvert.DeserializeObject<FooObject>(json);
这是异常:
Newtonsoft.Json.JsonSerializationException
HResult=0x80131500
Message=Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Test.PetObject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'pets.dog', line 4, position 10.
有没有办法将 pets 对象内的对象转换为对象数组?(除了在将 JSON 传递给 DeserializeObject 方法之前编辑它本身)
您的 JSON 文件包含一个宠物字典,而不是一个数组。因此,更改FooObject
类:
public class FooObject
{
[JsonProperty("foo")]
public string Foo { get; set; }
[JsonProperty("pets")]
public Dictionary<string, PetObject> Pets { get; set; }
// if you still need a list of pets, use this
public List<PetObject> PetsList => Pets.Values.ToList();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句