1

I'm trying to create a simple application through Lesson 6 in N+1 Days of MvvmCross application sample. But its failed in SimpleRestService while converting json Data serialization.

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

My Json data through Browser:

[{"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":"Waiting Approval","Id":"9"},{"Desc":"Cancelled","Id":"10"},{"Desc":"Not Resolved","Id":"8"}]

My Json data in application at 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\":\"Waiting Approval\",\"Id\":\"9\"},{\"Desc\":\"Cancelled\",\"Id\":\"10\"},{\"Desc\":\"Not Resolved\",\"Id\":\"8\"}]

Error Message shows as :

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

My Code part: Class Declaration:

public class BookSearchItem
{
    public string Desc { get; set; }
    public string Id { get; set; }
}
    public class BookSearchResult
{
   public List<BookSearchItem> items { get; set; }      
}

Binding Declaration:

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

Simple Rest Service For Common:

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

1 回答 1

1

您必须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);
于 2013-08-28T12:51:54.563 回答