Search code examples
c#jsonjson.netdeserialization

Deserialization JSON object vs. array


I get the following JSON-Message as a return from a REST-API:

{
   "result":{
      "CONTACT":[
         102565, 
         523652
      ],
      "COMPANY":[
         30302
      ]
   }
}

for deserializing I use Newtonsoft.Json with the following classes:

public class DuplicateResponseBody {
    [JsonProperty("result")]
    public ContactCompany Result { get; set; }
}

public class ContactCompany {
    [JsonProperty("CONTACT")]
    public int[] ContactIds { get; set; }
    [JsonProperty("COMPANY")]
    public int[] CompanyIds { get; set; }
}

this is working without problems.

But when there are no values, the REST-Response looks like

{
   "result":[]
}

the result is not an array and the deserialization would not working anymore. I cannot change the REST-API.

Does someone have an Idea, how can I solve the problem on the deserialization-step?


Solution

  • I don't think that you need any converters, it would be enough just to add a json constructor to your class

    public class DuplicateResponseBody
    {
        [JsonProperty("result")]
        public ContactCompany Result { get; set; }
        
        [Newtonsoft.Json.JsonConstructor]
        public  DuplicateResponseBody(JToken result)
        {
             if ( result.Type.ToString()!="Array")
             Result= result.ToObject<ContactCompany>();
        }
    
        public DuplicateResponseBody() {}
    }