RMR
RMR

Reputation: 629

How to switch between two classes as per response for deserialize json string?

I am working on xamarin.forms. I am facing issue during API call. I have one API for Login.

When email and password is valid then response is

{
    "status": true,
    "statusCode": 200,
    "response": {
        "Id": "83ae239e-764e-4cef-af86-363664a3a65a",
        "Email": "[email protected]",
        "EmailConfirmed": false,
        "PasswordHash": "AFetO7VdrveGEfVZEezldzkOkh6Xs0/JR18+0QDptO56UJzY5qgwpZcpudNM2cVxFA==",
        "SecurityStamp": "f062b486-f19a-4981-96a7-0fc72f17e99f",
        "PhoneNumber": null,
        "PhoneNumberConfirmed": false,
        "TwoFactorEnabled": false,
        "LockoutEndDateUtc": null,
        "LockoutEnabled": true,
        "AccessFailedCount": 0,
        "UserName": "[email protected]",
        "UserId": 5,
        "Name": "Rutul",
        "ZipCode": null,
        "CountryId": null,
        "IsDeleted": false,
        "CreatedDate": "2017-08-23T13:41:22"
    }
}

Json to C# class is:

public class Response
        {
            public string Id { get; set; }
            public string Email { get; set; }
            public bool EmailConfirmed { get; set; }
            public string PasswordHash { get; set; }
            public string SecurityStamp { get; set; }
            public object PhoneNumber { get; set; }
            public bool PhoneNumberConfirmed { get; set; }
            public bool TwoFactorEnabled { get; set; }
            public object LockoutEndDateUtc { get; set; }
            public bool LockoutEnabled { get; set; }
            public int AccessFailedCount { get; set; }
            public string UserName { get; set; }
            public int UserId { get; set; }
            public string Name { get; set; }
            public object ZipCode { get; set; }
            public object CountryId { get; set; }
            public bool IsDeleted { get; set; }
            public string CreatedDate { get; set; }
        }

        public class RootObject
        {
            public bool status { get; set; }
            public int statusCode { get; set; }
            public Response response { get; set; }
        }

IN "RootObject" class below property having return type "Response"

public Response response { get; set; }

When Email and Password are invalid then the response is :

{
    "status": false,
    "statusCode": 203,
    "response": "Invalid Email or Password."
}

json to c# class is :

public class RootObject
{
    public bool status { get; set; }
    public int statusCode { get; set; }
    public string response { get; set; }
}

In "RootObject" class below property having return type string

public string response { get; set; }

I am facing issue in deserializing object

Service Call function :

private async Task GetService_SignIn()
        {
            try
            {
                string url = ServiceURLs.SignIn + "email=" + txtEmail.Text + "&password=" + txtPassword.Text;
                var Service_response = await GetResponseFromWebService.GetResponse<SignIn.RootObject>(url);
                if (Service_response != null)
                {
                    if (Service_response.status)
                    {
                        // Application.Current.MainPage = new SideMenu();
                        Alert("Success", "Login success", "icon.png", Color.Green);
                    }
                    else
                    {
                        if (Service_response.statusCode == 417)
                        {
                            Alert("Alert", "WebServer Exception", "icon.png", Color.Red);
                        }
                        else if (Service_response.statusCode == 203)
                        {
                            Alert("Alert", "Invalid Email or Password", "icon.png", Color.Red);
                        }
                    }
                }
                else
                {
                    Alert("Alert", "WebServer not Responding", "icon.png", Color.Red);
                }
            }
            catch (WebException ex)
            {
                Alert("Exception", ex.Message, "icon.png", Color.Red);
            }
        } 

Common class for Getting Response:

public static async Task<T> GetResponse<T>(string URI) where T : class
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                HttpClient httpClient = new HttpClient();
                //httpClient.DefaultRequestHeaders.IfModifiedSince = DateTimeOffset.Now;
                //httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Token", "dc642a7f5bd64912");

                var request = new HttpRequestMessage(HttpMethod.Get, URI);

                if (request.Headers.CacheControl == null)
                {
                    request.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue();
                }

                request.Headers.CacheControl.NoCache = true;

                var response1 = await httpClient.SendAsync(request);
                if (response1 != null && response1.IsSuccessStatusCode)
                {
                    var responseString = await response1.Content.ReadAsStringAsync();

                    if (!string.IsNullOrWhiteSpace(responseString))
                    {
                        return JsonConvert.DeserializeObject<T>(responseString);
                    }
                }
            }
            return null;
        }

When email and password is invalid then I got exception from below line

return JsonConvert.DeserializeObject(responseString);

How to switch between two classes as per response? if I haven't deserialized json response how can know the status code?

How to handle this kind of setuation in c#?

Upvotes: 2

Views: 922

Answers (1)

Sharada
Sharada

Reputation: 13601

Assuming you are using Newtonsoft - you can add JsonConverter attribute in Response property of RootObject. The converter can detect if response is string (at run-time) and assign it to some property on Response instance.

More details here on how to create one and here on how to assign to property using attribute.

A sample json-converter would look like:

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

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        object retVal = new Object();
        if (reader.TokenType == JsonToken.StartObject)
        {
            var instance = (Response)serializer.Deserialize(reader, typeof(Response));
            retVal = instance;
        }
        else if (reader.TokenType == JsonToken.String)
        {
            string message = (string)serializer.Deserialize(reader);
            retVal = new Response { Message = message };
        }

        return retVal;
    }

    public override bool CanConvert(Type objectType)
    {
        return true;
    }
}

And, usage:

public class RootObject
{
    public bool status { get; set; }
    public int statusCode { get; set; }
    [JsonConverter(typeof(StringToResponseConverter))]
    public Response response { get; set; }
}

Upvotes: 4

Related Questions