【发布时间】:2017-09-14 22:33:40
【问题描述】:
我正在尝试使用 Newtonsoft.Json 反序列化嵌套在 Json 响应中的一些对象。我想将以下 Jsons Term 对象反序列化到一个列表中。我在 Json 响应中有很多 Term 对象,因此性能和紧凑性对我来说很重要。我也只想定义Term 类,因为我暂时不关心其他数据。
我为 Term 定义了一个模型:
public class Term
{
public string Known { get; set; }
public string Word { get; set; }
}
我的 Json 看起来像这样:
{
"myName":"Chris",
"mySpecies":"Cat",
"myTerms":
[
{
"Term":
{
"Known":"true",
"Word":"Meow"
}
},
{
"Term":
{
"Known":"false",
"Word":"Bark"
}
}
]
}
我的 C# 反序列化代码:
var response = await httpClient.GetAsync(uri);
string responseString = response.Content.ReadAsStringAsync().GetResults();
var searchTermList = JsonConvert.DeserializeObject<List<Term>>(responseString);
我收到的问题/错误是,不确定如何从 json 响应中获取这些术语:
{Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current
JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[CoreProject.Models.Term]' 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.
任何建议将不胜感激:)
【问题讨论】:
-
您是否为该结构的其他组件定义了模型?您提供的 json 不是术语列表,它是一个对象。您还需要定义更高级别的对象模型
-
@AaronRoberts 有没有办法只提取
Terms 的列表并反序列化它们? -
@visc 我将创建对象模型,然后使用 LINQ 选择您的术语列表。