【问题标题】:JSON.NET: Deserializing from JSON with LINQJSON.NET:使用 LINQ 从 JSON 反序列化
【发布时间】:2015-05-26 11:52:10
【问题描述】:

我有以下 json:

{[
  "{\"Id\":3,\"ParentName\":\"TicketController\",\"ChildName\":null,\"Body\":\"Ticket\",\"ParentId\":null,\"HasChildren\":true,\"imageUrl\":null}",
  "{\"Id\":0,\"ParentName\":\"TicketController\",\"ChildName\":\"MainPage\",\"Body\":\"HomePage\",\"ParentId\":3,\"HasChildren\":false,\"imageUrl\":null}",
  "{\"Id\":1,\"ParentName\":\"TicketController\",\"ChildName\":\"TicketList\",\"Body\":\"Requests\",\"ParentId\":3,\"HasChildren\":false,\"imageUrl\":null}",
  "{\"Id\":2,\"ParentName\":\"TicketController\",\"ChildName\":\"Responses\",\"Body\":\"Responses\",\"ParentId\":3,\"HasChildren\":false,\"imageUrl\":null}",
  "{\"Id\":3,\"ParentName\":\"TicketController\",\"ChildName\":\"UpdateResponse\",\"Body\":\"Edit\",\"ParentId\":3,\"HasChildren\":false,\"imageUrl\":null}",
  "{\"Id\":4,\"ParentName\":\"TicketController\",\"ChildName\":\"UpdateResponse\",\"Body\":\"Update\",\"ParentId\":3,\"HasChildren\":false,\"imageUrl\":null}",
  "{\"Id\":5,\"ParentName\":\"TicketController\",\"ChildName\":\"RequestDetail\",\"Body\":\"Detail\",\"ParentId\":3,\"HasChildren\":false,\"imageUrl\":null}",
  "{\"Id\":6,\"ParentName\":\"TicketController\",\"ChildName\":\"RequestDetail\",\"Body\":\"Save\",\"ParentId\":3,\"HasChildren\":false,\"imageUrl\":null}",
  "{\"Id\":7,\"ParentName\":\"TicketController\",\"ChildName\":\"DeleteRequest\",\"Body\":\"Delete\",\"ParentId\":3,\"HasChildren\":false,\"imageUrl\":null}"
]}

结果是通过用户在客户端选择一些复选框(KendoUI树视图女巫复选框)生成的:

var checkedNodes = [];
function checkedNodeIds(nodes) {
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].checked) {
            var page = {
                Id: nodes[i].Id,
                ParentName: nodes[i].ParentName,
                ChildName: nodes[i].ChildName,
                Body: nodes[i].Body,
                ParentId: nodes[i].ParentId,
                HasChildren: nodes[i].HasChildren,
                imageUrl: nodes[i].imageUrl
            };
            checkedNodes.push(JSON.stringify(page));
            console.log(nodes[i]);
        }

        if (nodes[i].hasChildren) {
            checkedNodeIds(nodes[i].children.view(), checkedNodes);
        }
    }
}
$('#btnSave').click(function() {
    var tv = $("#my-treeview").data("kendoTreeView");
    checkedNodeIds(tv.dataSource.view());
    var data = {};
    data.checks = JSON.stringify(checkedNodes);
    $.ajax({
        url: '@Url.Action("SaveTreeViewData", "Main", new {area = ""})',
        type: 'POST',
        data: data,
        dataType: 'json',
        success: function(result) {
            alert("Success");
        },
        error: function(result) {
            alert("Error");
        }
    });
});

在服务器端,我对parsing the json 结果使用了这种操作方法:

[HttpPost]
public ActionResult SaveTreeViewData(string checks) {
    //var result = JsonConvert.DeserializeObject<Page[]>(checks.Substring(1, checks.Length-2));
    var jsonArray = JArray.Parse(checks);
    IList < Page > pages = jsonArray.Select(p = > new Page {
        Id = (int) p["Id"],
        ParentName = (string) p["ParentName"],
        ChildName = (string) p["ChildName"] ? ? "NoChild",
        ParentId = (int) p["ParentId"],
        HasChildren = (bool) p["HasChildren"],
        Body = (string) p["Body"],
        imageUrl = (string) p["imageUrl"]
    }).ToList();

    return Json("ok");
}

但是当我点击保存按钮时,我得到了这个异常:

{"Cannot access child value on Newtonsoft.Json.Linq.JValue."}

有什么想法吗?

【问题讨论】:

  • ParentId = (int) p["ParentId"] 看起来很可疑...我看到至少一个元素带有 ParentId null .

标签: javascript c# json json.net


【解决方案1】:

数组中的每个元素只是另一个字符串 - 因此您还需要解析每个元素。例如:

IList<Page> pages = jsonArray
    .Select(text => JObject.Parse(text))
    .Select(p => new Page { ... })
    .ToList();

或者,更改您的 Javascript 代码以避免双重编码,因此您最终会得到以下 JSON:

{[
  {"Id":3,"ParentName":"TicketController",""ChildName"":null,"Body":"Ticket","ParentId":null,"HasChildren":true,"imageUrl":null},
  ...

]}

【讨论】:

  • 哇!非常感谢乔恩 :) PS:text 需要 .ToString() :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
相关资源
最近更新 更多