punkouter
punkouter

Reputation: 5366

Very simple attempt to deserialize JSON with JSON.NET does not work

I get the error below... Something is very wrong :( any ideas? (This is in a Windows Phone 8 app)

An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.DLL but was not handled in user code

And the code is

  string responseBody = @" {""HighScoreId"":1,""Name"":""Debra Garcia"",""Score"":2.23},{""HighScoreId"":2,""Name"":""Thorsten Weinrich"",""Score"":2.65}";

            GlobalHighScore s = JsonConvert.DeserializeObject<GlobalHighScore>(responseBody);

and the class is

  public class GlobalHighScore
{
    public int HighScoreId { get; set; }
    public string Name { get; set; }
    public double Score { get; set; }
}

Upvotes: 0

Views: 109

Answers (1)

Justin Niessner
Justin Niessner

Reputation: 245429

Your JSON has more than one object, and neither are in an array. You either need to remove one of the objects from the JSON or add them to an array and deserialize them properly:

string responseBody = 
    @"[
        {""HighScoreId"":1,""Name"":""Debra Garcia"",""Score"":2.23},
        {""HighScoreId"":2,""Name"":""Thorsten Weinrich"",""Score"":2.65}
    ]";

var highScores = 
    JsonConvert.DeserializeObject<List<GlobalHighScore>>(responseBody);

Upvotes: 1

Related Questions