Mrk Fldig
Mrk Fldig

Reputation: 4486

Deserialize JSON Array to object

I've been starting at this for a while and can't quite seem to get my head round it, essentially I have a JSON array which I want to decode into the Notifications object, the exception is:

"An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WpfApplication2.Notifications' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly."

public Notifications Notes;

// HTTP request gets the JSON below.

//EXCEPTION ON THIS LINE
Notes = JsonConvert.DeserializeObject<Notifications>(responseString);

    public class Notifications 
    {

        [JsonProperty("note_id")]
       public int note_id { get; set;}
        [JsonProperty("sender_id")]
        public int sender_id { get; set; }
        [JsonProperty("receiver_id")]
        public int receiver_id { get; set; }
        [JsonProperty("document_id")]
        public int document_id { get; set; }
        [JsonProperty("search_name")]
        public string search_name { get; set; }
        [JsonProperty("unread")]
        public int unread { get; set; }
    }

The Json retrieved is:

[
  {
    "note_id": "5",
    "sender_id": "3",
    "receiver_id": "1",
    "document_id": "102",
    "unread": "1"
  },
  {
    "note_id": "4",
    "sender_id": "2",
    "receiver_id": "1",
    "document_id": "101",
    "unread": "1"
  }
]

Upvotes: 0

Views: 229

Answers (2)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131180

Your call tries to deserialize a single object. The expected Json for such an object would be a dictionary of values, which is what the error message is saying.

You should try to deserialize to a IEnumerable-derived collection instead, eg an array or list:

Notifications[] Notes = JsonConvert.DeserializeObject<Notifications[]>(responseString);

or

IList<Notifications> Notes = JsonConvert.DeserializeObject<IList<Notifications>>(responseString);

Upvotes: 2

Charles Ouellet
Charles Ouellet

Reputation: 6518

You should deserialize it to a list:

public IList<Notifications> Notes;

Notes = JsonConvert.DeserializeObject<IList<Notifications>>(responseString);

Should work!

Upvotes: 2

Related Questions