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.
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.
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).
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With