json - MvvmCross:JSON 的反序列化错误

标签 json mvvm mvvmcross portable-class-library

我正在尝试通过 N+1 天的 MvvmCross 应用程序示例中的第 6 课创建一个简单的应用程序。但它的转换 json 数据时 SimpleRestService 失败 序列化。

private T Deserialize<T>(string responseBody)
{   // Error is here for deserilizing
    var toReturn = _jsonConverter.DeserializeObject<T>(responseBody);
    return toReturn;
}

我的 Json 数据通过浏览器 :

[{"Desc":"All","Id":"0"},{"Desc":"Assigned","Id":"2"},{"Desc":"In Progress","Id":"3"},{"Desc":"Resolved","Id":"4"},{"Desc":"Closed","Id":"5"},{"Desc":"Hold","Id":"6"},{"Desc":"低","Id":"8"},{"Desc":"等待审批","Id":"9"},{"Desc ":"已取消","Id":"10"},{"Desc":"未解决","Id":"8"}]

我的 Json 数据在 responsebody 的应用程序中:

[{\"Desc\":\"All\",\"Id\":\"0\"},{\"Desc\":\"Assigned\",\"Id\":\"2\"},{\"Desc\":\"In Progress\",\"Id\":\"3\"},{\"Desc\":\"Resolved\",\"Id\":\"4\"},{\"Desc\":\"Closed\",\"Id\":\"5\"},{\"Desc\":\"Hold\",\"Id\":\"6\"},{\"Desc\":\"低\",\"Id\":\"8\"},{\"Desc\":\"等待审批\",\"Id\":\"9\"},{\"Desc\":\"已取消\",\"Id\":\"10\"},{\"Desc\":\"未解决\",\"Id\":\"8\"}]

错误消息显示为:

{Newtonsoft.Json.JsonSerializationException: Cannot deserialize JSON array (i.e. [1,2,3]) into type 'Book.Core.Services.BookSearchResult'. The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList. To force JSON arrays to deserialize add the JsonArrayAttribute to the type. Path '', line 1, position 1. at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract) [0x00000] in :0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.Object existingValue, System.String reference) [0x00000] in :0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, System.Object existingValue) [0x00000] in :0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueNonProperty (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.JsonConverter converter, Newtonsoft.Json.Serialization.JsonContainerContract containerContract) [0x00000] in :0 at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in :0 at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in :0 at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in :0 etc.. }



我的代码部分:
类声明:
public class BookSearchItem
{
    public string Desc { get; set; }
    public string Id { get; set; }
}
    public class BookSearchResult
{
   public List<BookSearchItem> items { get; set; }      
}

绑定(bind)声明:
public void StartSearchAsync(string whatFor, Action<BookSearchResult> success, Action<Exception> error)
    {           
        string address = string.Format("http://192.168.0.76/eFACiLiTYPhone/MobileService/WinPhoneWCFService.svc/callstatustesting");
        _simpleRestService.MakeRequest<BookSearchResult>(address,"GET", success, error);
    }

普通的简单休息服务:
public class SimpleRestService :ISimpleRestService
{
    private readonly IMvxJsonConverter _jsonConverter;

    public SimpleRestService(IMvxJsonConverter jsonConverter)
    {
        _jsonConverter = jsonConverter;
    }

    public void MakeRequest<T>(string requestUrl, string verb, Action<T> successAction, Action<Exception> errorAction)
    {
        var request = (HttpWebRequest)WebRequest.Create(requestUrl);
        request.Method = verb;
        request.Accept = "application/json";

        MakeRequest(
           request,
           (response) =>
           {
               if (successAction != null)
               {
                   T toReturn;
                   try
                   {
                       toReturn = Deserialize<T>(response);
                   }
                   catch (Exception ex)
                   {
                       errorAction(ex);
                       return;
                   }
                   successAction(toReturn);
               }
           },
           (error) =>
           {
               if (errorAction != null)
               {
                   errorAction(error);
               }
           }
        );
    }

    private void MakeRequest(HttpWebRequest request, Action<string> successAction, Action<Exception> errorAction)
    {
        request.BeginGetResponse(token =>
        {
            try
            {
                using (var response = request.EndGetResponse(token))
                {
                    using (var stream = response.GetResponseStream())
                    {
                        var reader = new StreamReader(stream);
                        successAction(reader.ReadToEnd());
                    }
                }
            }
            catch (WebException ex)
            {
                Mvx.Error("ERROR: '{0}' when making {1} request to {2}", ex.Message, request.Method, request.RequestUri.AbsoluteUri);
                errorAction(ex);
            }
        }, null);
    }

    private T Deserialize<T>(string responseBody)
    {
        var toReturn = _jsonConverter.DeserializeObject<T>(responseBody);
        return toReturn;
    }
}

最佳答案

您必须使用正确的 T为您的 Json 调用 - 您不能简单地使用 BookSearchResult对于所有 Json 调用。

您可以使用 http://json2csharp.com/ 等工具为您生成 CSharp 类 - 例如

public class RootObject
{
    public string Desc { get; set; }
    public string Id { get; set; }
}

然后您可以将其用作:
var myItems = service.Deserialize<List<RootObject>>(jsonText);

关于json - MvvmCross:JSON 的反序列化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18488310/

相关文章:

c# - GridSplitter移至外部资源(UserControl)时的行为有所不同

android - 在 TabHost 上按下 MonoDroid MVVMCross 句柄后退按钮

c# - 如何防止多次连续按下 'Enter'键

xamarin - MVVM Xamarin Forms,最适合在等待服务调用几分钟响应时将函数保留在内存中

node.js - 专业人员如何处理数千、数十万甚至数百万个 JSON 对象? Node .js

java - java如何创建json格式

ios - 防止View进入历史栈

android - MvxListView 未绑定(bind)到 MvxItemTemplate

javascript - 美化 JSON 是什么意思

java - Jackson:为 Map 数据结构注册自定义 XML 序列化程序