0

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"
  }
]
2
  • Maybe because your array is unnamed, i.e. that it should be something like { "arrayname": [ {...}, {...} ] } ? Commented Oct 23, 2014 at 13:20
  • You need to deserialize to an array or collection Commented Oct 23, 2014 at 13:27

2 Answers 2

2

You should deserialize it to a list:

public IList<Notifications> Notes;

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

Should work!

Sign up to request clarification or add additional context in comments.

2 Comments

Could also be an array.
Erm i'm not sure which one to pick here they both work!
2

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

1 Comment

I've upvoted this as it also works, Charles got there just before though hope this seems fair?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.