1

I have a JSON Response that sometimes returns an array when there are more than 1 elements and just an object when there is only one element.

Something Like this:-

"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": ""
            }
          ]
        },

Sometimes Like this:-

"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": ""
            }
}

The trouble is when I am deserializing the object in C#, I get an error saying "Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List1[JLL.BTP.DealioService.Models.Dealio.DealAllocation]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.`"

How to overcome this problem. I want to have an Response Class and want to deserialize the JSON response to the Response Class.

Any suggestions would be greatly appreciated !!

SaiBand
  • 5,025
  • 15
  • 57
  • 76
  • 2
    Have you seen https://stackoverflow.com/questions/5224697/deserializing-json-when-sometimes-array-and-sometimes-object - if I were going to vote this q as a duplicate, it's the one I'd peg – Caius Jard May 10 '19 at 03:28

1 Answers1

2

I am not sure which Json parser you're using, but if you could use "Newtonsoft.Json" one, I think maybe could try something like

JObject payload = JObject.Parse(payload);

var result = payload["JLLBrokerAllocations"]["JLLBrokerAllocation"].Children().ToList();
Ted Zhang
  • 341
  • 2
  • 6