【发布时间】:2015-01-18 19:16:10
【问题描述】:
我在尝试确定如何使我的序列化能够正确访问单个结果以及数组时遇到了麻烦。
当我在服务器上进行 REST 调用时,有时它会返回一个模型数组,但如果搜索结果只有一个模型,则不会作为错误返回。这是当我得到一个我无法反序列化的异常时,因为对象属性需要一个数组,而是接收一个对象。
有没有办法定义我的类,以便它在返回时可以处理 ns1.models 类型的单个对象而不是对象数组?
[JsonObject]
public class Responses
{
[JsonProperty(PropertyName = "ns1.model")]
public List<Model> Model { get; set; }
}
可以反序列化的响应:
{"ns1.model":[
{"@mh":"0x20e800","ns1.attribute":{"@id":"0x1006e","$":"servername"}},
{"@mh":"0x21a400","ns1.attribute":{"@id":"0x1006e","$":"servername2"}}
]}
无法序列化的响应(因为 JSON 仅包含一个“ns1.model”):
{"ns1.model":
{"@mh":"0x20e800","ns1.attribute":{"@id":"0x1006e","$":"servername"}}
}
例外:
Newtonsoft.Json.JsonSerializationException was unhandled HResult=-2146233088 Message=Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ConsoleApplication1.Model]' 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 '['ns1.model-response-list'].['ns1.model-responses'].['ns1.model'].@mh', line 1, position 130
【问题讨论】:
标签: c# json serialization json.net deserialization