json.deserialize возвращает null + xamarin.forms - PullRequest
0 голосов
/ 02 мая 2018

Я получаю ответный текст от вызова веб-API

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

я пытаюсь десериализовать это так

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

это мой класс c #:

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; }
}

Полный ИСТОЧНИК КОД:

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; }
}

}

но я получаю нулевое значение в результате. Кто-нибудь может помочь. Что я делаю не так

спасибо.

1 Ответ

0 голосов
/ 02 мая 2018

Это не будет работать:

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

Вы десериализуете string responseBodyAsString для объекта типа RootObject. После этого вы конвертируете объект в строку и пытаетесь десериализовать эту строку (что бы она ни содержала) в T.

Я предполагаю, что result.response должны быть вашими данными.

Я не уверен, в чем ваша проблема. Возможно, вы забыли назвать тип, который хотите десериализовать.

Вот несколько примеров десериализации:

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; }
}
...