收到错误消息“无法反序列化当前JSON数组"使用Json.Net反序列化时 [英] Getting an error "Cannot deserialize the current JSON array" when deserializing using Json.Net

查看:128
本文介绍了收到错误消息“无法反序列化当前JSON数组"使用Json.Net反序列化时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:

[
  {
    "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
  }
]

我在模型中的课程

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

我使用Json.Net,我想将波纹管转换为Json Oject.

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

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

但是它出错了:

Newtonsoft.Json.dll中发生了类型为'Newtonsoft.Json.JsonSerializationException'的异常,但未在用户代码中进行处理
附加信息:无法将当前JSON数组(例如[1,2,3])反序列化为类型'QuoteAPI.Models.CPacket',因为该类型需要JSON对象(例如{"name":"value"})才能正确反序列化

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.

推荐答案

您的JSON表示 CPacket 对象的数组,而不仅仅是单个对象.您需要反序列化到列表中.

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

这篇关于收到错误消息“无法反序列化当前JSON数组"使用Json.Net反序列化时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆