【发布时间】:2014-11-02 02:54:44
【问题描述】:
我使用的其中一个 JSON API 返回响应,该响应会根据查询返回的结果数量而改变其数据结构。我从 C# 中使用它并使用 JSON.NET 反序列化响应。
这是从 API 返回的 JSON
多重结果响应:
{
"response": {
"result": {
"Leads": {
"row": [
{
"no": "1",
...
...
...
单一结果响应:
{
"response": {
"result": {
"Leads": {
"row": {
"no": "1",
...
...
...
注意“行”节点的区别,在多个结果的情况下是数组,在单个结果的情况下是对象。
这里是我用来反序列化这些数据的类
类:
public class ZohoLeadResponseRootJson
{
public ZohoLeadResponseJson Response { get; set; }
}
public class ZohoLeadResponseJson
{
public ZohoLeadResultJson Result { get; set; }
}
public class ZohoLeadResultJson
{
public ZohoDataMultiRowJson Leads { get; set; }
}
public class ZohoDataMultiRowJson
{
public List<ZohoDataRowJson> Row { get; set; }
}
public class ZohoDataRowJson
{
public int No { get; set; }
...
}
“Multiple Result Response”反序列化没有任何问题,但是当响应中只有一个结果时,由于数据结构的变化,无法反序列化响应。我得到一个例外
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON
object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[MyNamespace.ZohoDataRowJson]'
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 'response.result.Notes.row.no', line 1, position 44.
有没有办法在 Json.Net 中使用一些属性来处理这个问题,并且希望不必编写转换器?
【问题讨论】:
-
感谢@L.B 提供链接以及链接问题中的答案。
-
@L.B.在 ReadJson 方法中 reader.ValueType 始终为空。在这种情况下,我必须使用 Reader.TokenType,即 StartArray 或 StartObject。此外,在这两种情况下,反序列化都将继续。我想发布一个答案,因为它与两个链接的答案略有不同。我还想命名供应商,这样可以帮助未来的用户遇到同样的问题。
-
我重新打开了这个问题...
-
谢谢@L.B.添加了答案。