我有json喜欢
{
"list": [
{
"id": 1,
"reference": null
},
{
"id": 2,
"reference": [
{
"name": name,
"data": "data"
}
]
}
]
}
我创建了课程
class MyList
{
[JsonProperty(PropertyName = "list")]
public IList<MyObject> list;
}
class MyObject
{
[JsonProperty(PropertyName = "id")]
public int id;
[JsonProperty(PropertyName = "reference")]
public IList<Reference> reference = null;
}
class Reference
{
[JsonProperty(PropertyName = "name")]
public string name;
[JsonProperty(PropertyName = "data")]
public string data;
}
并使用
MyList mylist = Newtonsoft.Json.JsonConvert.DeserializeObject<MyList>(response,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ObjectCreationHandling = ObjectCreationHandling.Replace,
DefaultValueHandling = DefaultValueHandling.Ignore,
});
我得到了异常
无法将当前JSON对象(例如{“name”:“value”})反序列化为类型'System.Collections.Generic.IList`1 [SBM.Actions.WebServices.WorkCenter.API.ResManJsonClient + MenuItem]',因为该类型需要一个JSON数组(例如[1,2,3])才能正确反序列化。
要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,使其成为普通的.NET类型(例如,不是像整数这样的基本类型,而不是可以从JSON对象反序列化的集合类型,如数组或List)。 JsonObjectAttribute也可以添加到类型中以强制它从JSON对象反序列化。
路径'列表[0] .myobject [0] .reference.name',第1行,位置*。
如何处理这样的jsons?
答案 0 :(得分:0)
正如@Andrew Whitaker在评论中指出的那样,您的JSON无效。需要引用name
属性的值。
在test.json文件中,您有:
"name": MyName,
应该是:
"name": "MyName",
解决了这个问题后,您的测试项目运行正常(没有错误)。