Neelam Prajapati
Neelam Prajapati

Reputation: 3802

json.deserialize returns null + xamarin.forms

i am getting response text like this from web api call

{
    "response":{"numFound":4661,"start":0,"maxScore":6.3040514,"docs":[..]  }
}

i am trying to deserialize it like this

var result = JsonConvert.DeserializeObject<RootObject>(responseBodyAsText);

this is my c# class:

public class Doc
{
public string id { get; set; }
public string journal { get; set; }
public string eissn { get; set; }
public DateTime publication_date { get; set; }
public string article_type { get; set; }
public List<string> author_display { get; set; }
public List<string> @abstract { get; set; }
public string title_display { get; set; }
public double score { get; set; }
}


 public class Response
{
public int numFound { get; set; }
public int start { get; set; }
public double maxScore { get; set; }
public List<Doc> docs { get; set; }
}


public class RootObject
{
public Response response { get; set; }
}

Full SOURCE CODE:

namespace CrossSampleApp1.Common
{
public class ServiceManager<T>
{
    public delegate void SucessEventHandler(T responseData, bool 
      HasMoreRecords = false);
    public delegate void ErrorEventHandler(ErrorData responseData);

    public event SucessEventHandler OnSuccess;
    public event ErrorEventHandler OnError;

    public async Task JsonWebRequest(string url, string contents, HttpMethod methodType, string mediaStream = "application/json")
    {
        bool isSuccessRequest = true;
        string responseBodyAsText = string.Empty;
        try
        {

            HttpClientHandler handler = new HttpClientHandler();
            using (HttpClient httpClient = new HttpClient(handler))
            {
                HttpRequestMessage message = new HttpRequestMessage(methodType, url);
                if (methodType == HttpMethod.Post)
                {
                    message.Headers.ExpectContinue = false;
                    message.Content = new StringContent(contents);
                    message.Content.Headers.ContentLength = contents.Length;
                    message.Content.Headers.ContentType = new MediaTypeHeaderValue(mediaStream);
                }

                httpClient.Timeout = new TimeSpan(0, 0, 10, 0, 0);
                HttpResponseMessage response = await httpClient.SendAsync(message);
                response.EnsureSuccessStatusCode();

                responseBodyAsText = response.Content.ReadAsStringAsync().Result;
            }
        }
        catch (HttpRequestException hre)
        {
            //responseBodyAsText = "Exception : " + hre.Message;
            responseBodyAsText = "Can't Connect (Please check your network connection)";
            isSuccessRequest = false;
        }
        catch (Exception ex)
        {
            //  responseBodyAsText = "Exception : " + ex.Message;
            responseBodyAsText = "Can't Connect (Please check your network connection)";
            isSuccessRequest = false;
        }

        try
        {
            if (isSuccessRequest)
            {
                if (typeof(T) == typeof(string))
                {
                    OnSuccess?.Invoke((T)(object)responseBodyAsText);
                }
                else if (typeof(T) == typeof(ServiceResponse))
                {
                    T result = JsonConvert.DeserializeObject<T>(responseBodyAsText);
                    OnSuccess?.Invoke(result);
                }
                else
                {
                    var result = JsonConvert.DeserializeObject<RootObject>(responseBodyAsText);
                    var data = JsonConvert.DeserializeObject<T>(Convert.ToString(result));
                    OnSuccess?.Invoke(data);

                }
            }
            else
            {
                OnError?.Invoke(new ErrorData
                {
                    ErrorText = responseBodyAsText
                });

            }
        }
        catch (Exception e)
        {
            OnError?.Invoke(new ErrorData
            {
                ErrorText = e.Message
            });
        }
    }

}

public class ErrorData : EventArgs
{
    public string ErrorText { get; set; }
    public bool Status { get; set; }
}

}

but i am getting null value in result.can anyone help.what i am doing wrong

thank you.

Upvotes: 1

Views: 609

Answers (1)

kara
kara

Reputation: 3455

This will not work:

var result = JsonConvert.DeserializeObject<RootObject>(responseBodyAsText);
var data = JsonConvert.DeserializeObject<T>(Convert.ToString(result));
OnSuccess?.Invoke(data);

You deserialize a string responseBodyAsString to an object of type RootObject. Afterwards you convert the object to string and try to deserialize this string (whatever it may contain) to T.

I'm guessing that result.response should be your data.

I'm not sure what you problem is. Perhaps that you forgot to name the type which you want to deserialize.

Here some example deserialization:

static void Main(string[] args)
{
    // Example-data
    string jsonInput = "{ \"response\":{\"numFound\":4661,\"start\":0,\"maxScore\":6.3040514,\"docs\":[\"a\",\"b\"] } }";
    // deserialize the inputData to out class "RootObject"
    RootObject r = JsonConvert.DeserializeObject<RootObject>(jsonInput);

    // Let's see if we got something in our object:
    Console.WriteLine("NumFound: " + r.response.numFound);
    Console.WriteLine("Start: " + r.response.start);
    Console.WriteLine("MaxScrote: " + r.response.maxScore);
    Console.WriteLine("Docs: " + string.Join(", ", r.response.docs));

    Console.WriteLine("-- let's have a look to our Deserializer without giving a type --");

    object o = JsonConvert.DeserializeObject("{ \"response\":{\"numFound\":4661,\"start\":0,\"maxScore\":6.3040514,\"docs\":[\"a\",\"b\"] } }");
    Console.WriteLine("Type: " + o.GetType());
    JObject j = o as JObject;
    Console.WriteLine(j["response"]);
    Console.WriteLine("NumFound: " + j["response"]["numFound"]);
    Console.WriteLine("Start: " + j["response"]["start"]);
    Console.WriteLine("MaxScrote: " + j["response"]["maxScore"]);
    Console.WriteLine("Docs: " + String.Join(", ", j["response"]["docs"].Select(s => s.ToString())));
}

public class Response
{
    public int numFound { get; set; }
    public int start { get; set; }
    public double maxScore { get; set; }
    public List<string> docs { get; set; }
}

public class RootObject
{
    public Response response { get; set; }
}

Upvotes: 1

Related Questions