Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an error "Cannot deserialize the current JSON array" when deserializing using Json.Net

Tags:

json

c#

json.net

I have a string:

[
  {
    "key": "key1",
    "value": "{'Time':'15:18:42','Data':'15:18:42'}",
    "duration": 5
  },
  {
    "key": "key1",
    "value": "{'Time':'15:18:42','Data':'15:18:42'}",
    "duration": 5
  }
]

My class in Models:

public class CPacket
{
    public string key { get; set; }
    public string value { get; set; }
    public int duration { get; set; }
}

I use Json.Net, I want to convert string bellow to Json Oject.

CPacket c = JsonConvert.DeserializeObject<CPacket>(strPostData);

But it error:

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'QuoteAPI.Models.CPacket' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

like image 949
Ta No Bi Avatar asked Mar 05 '15 03:03

Ta No Bi


People also ask

Can t deserialize JSON array?

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from JSON array.

What is Deserializing JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

How do you represent an array of objects in JSON?

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.


1 Answers

Your JSON represents an array of CPacket objects, not just a single object. You need to deserialize into a list.

List<CPacket> list = JsonConvert.DeserializeObject<List<CPacket>>(strPostData);
like image 192
Brian Rogers Avatar answered Oct 07 '22 12:10

Brian Rogers