我有一个JSON响应,当元素多于1个时,有时会返回一个数组;而当元素只有1个时,则仅返回一个对象。
类似这样的东西:-
"JLLBrokerAllocations": {
"JLLBrokerAllocation": [
{
"AllocPercent": 50,
"Amount": 4,
"Email": "",
"EmpId": 214309,
"EmpLoginId": "Carlin.Power",
"EmpName": "Power, Carlin",
"Id": 1147842,
"LeadBroker": true,
"MarketId": "AM0001",
"Markets": "",
"OpUnitId": 250050,
"OpUnits": ""
},
{
"AllocPercent": 50,
"Amount": 4,
"Email": "",
"EmpId": 999111,
"EmpLoginId": "Sai.Abhiram",
"EmpName": "Abhiram, Sai",
"Id": 1147843,
"LeadBroker": true,
"MarketId": "AM2900",
"Markets": "",
"OpUnitId": 200028,
"OpUnits": ""
}
]
},
有时是这样的:-
"JLLBrokerAllocations": {
"JLLBrokerAllocation":
{
"AllocPercent": 50,
"Amount": 4,
"Email": "",
"EmpId": 214309,
"EmpLoginId": "Carlin.Power",
"EmpName": "Power, Carlin",
"Id": 1147842,
"LeadBroker": true,
"MarketId": "AM0001",
"Markets": "",
"OpUnitId": 250050,
"OpUnits": ""
}
}
问题是当我在C#中反序列化对象时,出现错误消息“ Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List
1 [JLL.BTP.DealioService.Models.Dealio.DealAllocation]”,因为该类型需要JSON数组(例如[1,2,3])正确反序列化。”“
如何克服这个问题。我想要一个响应类,并想反序列化JSON响应到响应类。
任何建议将不胜感激!
答案 0 :(得分:0)
我不确定您使用的是哪个Json解析器,但是如果您可以使用“ Newtonsoft.Json”,我想也许可以尝试类似的
JObject payload = JObject.Parse(payload);
var result = payload["JLLBrokerAllocations"]["JLLBrokerAllocation"].Children().ToList();