如何将类似对象的 json 对象反序列化为 C# list<T>
How deserialize json object of like objects to c# list<T>
我有 json 这样的回复:
{
"val1":{
"id":"1",
"value":"val"
},
"val2":{
"id":"2",
"value":"otherVal"
}
}
我如何将此有效负载反序列化为 SimplyObject 的通用列表,其中 SimplyObject 是
public class SimpleObject {
public int Id {get;set;}
public string Value {get;set;}
}
当我尝试将此有效负载反序列化为 SimpleObject 列表时出现以下错误:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[SimpleObject]' 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) 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.
您可以使用 Dictionary
反序列化您的 JSON,例如:
var result = JsonConvert.DeserializeObject<Dictionary<string, SimpleObject>>(json);
并像这样使用它,例如:
foreach (var item in result)
{
Console.WriteLine($"Item: {item.Key} has Id of {item.Value.Id} and value of {item.Value.Value}");
}
我有 json 这样的回复:
{
"val1":{
"id":"1",
"value":"val"
},
"val2":{
"id":"2",
"value":"otherVal"
}
}
我如何将此有效负载反序列化为 SimplyObject 的通用列表,其中 SimplyObject 是
public class SimpleObject {
public int Id {get;set;}
public string Value {get;set;}
}
当我尝试将此有效负载反序列化为 SimpleObject 列表时出现以下错误:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[SimpleObject]' 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) 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.
您可以使用 Dictionary
反序列化您的 JSON,例如:
var result = JsonConvert.DeserializeObject<Dictionary<string, SimpleObject>>(json);
并像这样使用它,例如:
foreach (var item in result)
{
Console.WriteLine($"Item: {item.Key} has Id of {item.Value.Id} and value of {item.Value.Value}");
}