1

I'm parsing a JSON string into an ObservableCollection, but when I do it Json.net throws this error:

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.

My DataModel, ViewModel and Loading are below:

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

Loading/ViewModel:

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

I've tried setting the ObservableCollection's to IList/ICollection's to no avail.

edit: Here is the json that I am parsing: http://pastebin.com/QVnikitV

1 Answer 1

2

Your positions field in the C# code represents a single object of type Position. Your JSON object's positions field represents an array.

So your C# code would need to be changed to an array to match:

public Position[] positions { get; set; }
Sign up to request clarification or add additional context in comments.

2 Comments

And it works perfectly. Thank you very much, can't believe I overlooked something so small.
No problem - sometimes it just takes a second set of eyes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.