Home > database >  JSON Deserialization to wrong object class passing
JSON Deserialization to wrong object class passing

Time:02-18

I have 2 classes that represent 2 Json responses in case of error or success.

private class SuccessResponse
    {
        public string message { get; set; }
        public bool sent { get; set; }
        public string id { get; set; }
    }

and

private class ErrorResponse
    {
        public string error { get; set; }
    }

I use try/catch block to determine which kind of response is by trying to deserialize to SuccessResponse object, the idea is if it fails it's an ErrorResponse type of object and gets deserialized in catch block.

Json string looks like this: {\"error\":\"Instance \\\"123\\\" doesn't exist.\"}

This type of determination worked for me in the past projects, without any issues.

The problem is occurring in try block, deserialization to SuccessResponse is passing without any exceptions raised, object returned by deserialization is empty, having only default values, when it should be caught and deserialized in the catch block

I have tried, serializing it before deserialization, replacing backslashes with "", adding JsonProperty attributes, but it still keeps "passing" deserialization and returning an empty SuccessResponse object.

Here is the try/catch:

try
{
  var trySuccess = Newtonsoft.Json.JsonConvert.DeserializeObject<SuccessResponse>(resp);

}
catch
{
  var tryError = Newtonsoft.Json.JsonConvert.DeserializeObject<ErrorResponse>(resp);

  Log.Error($"ERROR FROM REMOTE SERVER: {tryError.error}");
}

CodePudding user response:

make one class ( use this code or use inheritance after making classes protected instead of private)

private class Response
    {
        public string message { get; set; }
        public bool sent { get; set; }
        public string id { get; set; }
        public string error { get; set; }
    }

        //or 

private class SuccessResponse:ErrorResponse
    {
        public string message { get; set; }
        public bool sent { get; set; }
        public string id { get; set; }
    }

and code

var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Response>(resp);

if (!string.IsNullOrEmpty(result.error) Log.Error($"ERROR FROM REMOTE SERVER: {result.error}");

  • Related