2012-12-18 119 views
1

我解析一个JSON字符串变成一个ObservableCollection,但是当我做Json.net抛出这个错误:Json.net反序列化错误

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MVPTracker.ViewModels.DataModels+League+Position' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

我的DataModel,视图模型和加载低于:

的DataModel:

public class League 
    { 
     public string name { get; set; } 
     public string code { get; set; } 
     public string imageUrl { get; set; } 
     public Position positions = new Position(); 

     public class Position 
     { 
      public string name { get; set; } 
      public string code { get; set; } 
      public string imageUrl { get; set; } 
      public string[] statistics { get; set; } 
     } 
    } 

加载/视图模型:

private ObservableCollection<DataModels.League> _leagues = new ObservableCollection<DataModels.League>(); 
    public ObservableCollection<DataModels.League> Leagues 
    { 
     get { return _leagues; } 
     set { _leagues = value; NotifyPropertyChanged("Leagues"); } 
    } 

    public async void Load() 
    { 
     string leaguesJSON = await ServerConnector.LoadOrganizations(); 

     Leagues.Clear(); 
     Leagues = JsonConvert.DeserializeObject<ObservableCollection<DataModels.League>>(leaguesJSON); 
    } 

我试着设置ObservableCollection的IList/ICollection的无济于事。

编辑:这是我解析JSON:http://pastebin.com/QVnikitV

回答

2

在C#代码你positions字段表示Position类型的单个对象。您的JSON对象的positions字段表示一个数组。

所以你的C#代码将需要更改到一个数组匹配:

public Position[] positions { get; set; } 
+0

它完美的作品。非常感谢,不敢相信我忽视了这么小的事情。 –

+0

没问题 - 有时只需要第二组眼睛。 –