【发布时间】:2021-12-23 23:12:25
【问题描述】:
我目前正在接收从 JsTree 生成的以下数组字符串:
"[
{
"id":"j1_1",
"text":"Root node 1",
"icon":true,
"li_attr":{
"id":"j1_1"
},
"a_attr":{
"href":"#",
"id":"j1_1_anchor"
},
"data":{
},
"children":[
{
"id":"j1_2",
"text":"Child 1",
"icon":true,
"li_attr":{
"id":"j1_2"
},
"a_attr":{
"href":"#",
"id":"j1_2_anchor"
},
"data":{
},
"children":[
]
}
]
}
]"
我正在尝试使用反序列化以下项目
JsTreeModel aaa = Newtonsoft.Json.JsonConvert.DeserializeObject<JsTreeModel>(json);
JsTreeModel 是这个类:
public class JsTreeModel
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("text")]
public string text { get; set; }
[JsonProperty("icon")]
public string icon { get; set; }
[JsonProperty("li_attr")]
public string li_attr { get; set; }
[JsonProperty("a_attr")]
public string a_attr { get; set; }
[JsonProperty("data")]
public string data { get; set; }
}
但我得到了错误`:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'AccesosWeb.Entidad.JsTree.JsTreeModel' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
我认为问题在于课程的结构,但我不知道如何构建它。
【问题讨论】:
-
仔细阅读消息,并查看您的 JSON。请注意您的 JSON 如何以
[和]开头和结尾?这是什么意思?这意味着它是一个collection,一个数组。那么你应该在 C# 中反序列化到什么?一个集合!例如:一个列表、一个数组等。你当前反序列化成什么?一个对象。JsTreeModel是一个object,表示它对应于以{开头并以}结尾的JSON。 -
正如@Llama 所写 - 您的 json 是一个数组,因此请尝试使用
DeserializeObject<List<JsTreeModel>>(json)。 -
谢谢你们。将其更改为列表后,尝试读取
li_attr之类的字段时出现另一个错误,因此我还在下面构建了类似于 Leandro Bardelli 解决方案的类,以添加实体以正确表示 json 数据。 (除了我必须做一些更正,因为它在他发布时没有正确表示它)。
标签: c# json jstree json-deserialization