无法反序列化 - JSON.NET - Xamarin

时间:2015-10-22 19:30:00

标签: json forms api xamarin

我正在努力解决以下信息。同一个应用程序中的其他JSON对象可以正常工作。

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array
(e.g. [1,2,3]) into type 'Monkeys.Models.Rootobject' because the type requires a JSON
object (e.g. {"name":"value"}) to deserialize correctly.

我通过网络浏览器从API获得以下输出:

[{"Id":"1","Name":"Monkey 1","Location":null,"Details":null,"SKU":null,"Size":null,
"Color":null,"Image":null,"Brand":null,"NameSort":"M"},{"Id":"2","Name":"Monkey 2",
"Location":null, "Details":null,"SKU":null,"Size":null,"Color":null,"Image":null,
"Brand":null,"NameSort":"M"}]

我的应用中的模型:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Monkeys.Models
{
  public class Monkey
  {
    public string Id { get; set; }
    public string Name {get;set;}
    public string Location { get; set; }
    public string Details { get; set; }
    //URL for our monkey image!
    public string SKU { get; set; }
    public string Size { get; set; }
    public string Color { get; set; }
    public string Image { get; set; }

    public string Brand { get; set; }

    public string NameSort
    {
        get
        {
            if (string.IsNullOrWhiteSpace(Name) || Name.Length == 0)
                return "?";

            return Name[0].ToString().ToUpper();
        }
    }
}

 public class Rootobject
 {
    public Monkey[] monkeys { get; set; }
 }
}



The App:

using System;
using System.Net;
using Newtonsoft.Json;
using System.Threading.Tasks;
using Monkeys.Models;
using System.Collections.Generic;

namespace Monkeys.Apis 
{


public class GetMonkeys
{
    public GetMonkeys()
    {
    }


    public async Task<Monkey[]> GetMonkeysAsync()
    {

        var client = new System.Net.Http.HttpClient();

        client.BaseAddress = 
new Uri("https://microsoft-                                             apiappce13ac35390d40a684dd6ab72a9eef8f.azurewebsites.net:443/");
        var response = await client.GetAsync("api/Monkey");

        var earthquakesJson = response.Content.ReadAsStringAsync().Result;


        var rootobject = JsonConvert.DeserializeObject<Rootobject>        (earthquakesJson);


        return rootobject.monkeys;

    }


}

}

1 个答案:

答案 0 :(得分:1)

你的json数据是一个Monkey数组。试试这个

// monkeys will be a List<Monkey>
var monkeys = JsonConvert.DeserializeObject<List<Monkey>>(earthquakesJson);