Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize json string to c# object using newtonsoft

I have been working with the project, where i have to make external RESTful service call to get some data.

The problem i'm facing here is, the response i'm getting from the service is different on different scenario. For example.

On one scenario, i'm getting below response

{  
   "id":3000056,
   "posted_date":"2016-04-15T07:16:47+00:00",
   "current_status":"initialized",
   "customer":{  
        "name" : "George",
        "lastName" : "Mike"
   },
   "application_address":{
        "addressLine1" : "Lin1",
        "addressLine2" : "Lin2",
   }

}

In the other scenario, im getting below response

 {  
   "id":3000057,
   "posted_date":"2016-04-15T07:16:47+00:00",
   "current_status":"initialized",
   "customer":[],
   "application_address":[]

}

The problem here is, i have below model, and i'm deserializing it by newtonsoft deserailization.

public class Response
    {

        [JsonProperty("id")]
        public int Id { get; set; }

        [JsonProperty("posted_date")]
        public DateTime PostedDate { get; set; }

        [JsonProperty("current_status")]
        public string CurrentStatus { get; set; }

        [JsonProperty("customer")]
        public Customer Customer { get; set; }

        [JsonProperty("application_address")]
        public ApplicationAddress ApplicationAddress { get; set; }


    }


public Class Customer
{

    public string name { get; set; }
    public string lastName { get; set; }
}

public classs ApplicationAddress
{
public string addreesLine1{ get; set; }
public string addreesLine1{ get; set; }
}

For the first response, it will desrialize. But for the second response, the response is not getting deserialized as the response contains [] for Customer and ApplicationAddrees object. While deserializing, it is treating as a array, but actually it is not.

Note : Below code i'm using for Deserializing. Response response = JsonConvert.DeserializeObject(result);

Is there any configuration we can do before serializing? Is newtonsoft facilitate that feature?

Thanks .

like image 429
PaRsH Avatar asked Jan 21 '26 12:01

PaRsH


1 Answers

If you are sure that there will be no arrays in this properties, than you can consider using JsonConverter like this:

public class FakeArrayToNullConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return false;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            return null;
        }
        return  token.ToObject<T>();

    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

And then put additional attribure to your model:

    [JsonProperty("customer")]
    [JsonConverter(typeof(FakeArrayToNullConverter<Customer>))]
    public Customer Customers { get; set; }

    [JsonProperty("application_address")]
    [JsonConverter(typeof(FakeArrayToNullConverter<ApplicationAddress>))]
    public ApplicationAddress ApplicationAddressList { get; set; }

And when in your JSON string for this properties it will be an array [], you will simply deserialize it with null object.

like image 82
gos Avatar answered Jan 23 '26 03:01

gos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!