简体   繁体   English

json.deserialize返回null + xamarin.forms

[英]json.deserialize returns null + xamarin.forms

i am getting response text like this from web api call 我正在从Web api调用中获取这样的响应文本

{
    "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: 这是我的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; }
}

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. 谢谢。

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 . 您将string responseBodyAsString反序列RootObject类型的对象。 Afterwards you convert the object to string and try to deserialize this string (whatever it may contain) to T. 之后,将对象转换为字符串,然后尝试将此字符串(无论可能包含什么)反序列化为T。

I'm guessing that result.response should be your data. 我猜那个result.response应该是您的数据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM