【问题标题】:Serialize an ASP.NET MVC model in JSON在 JSON 中序列化 ASP.NET MVC 模型
【发布时间】:2012-12-04 07:36:07
【问题描述】:

我有一个这样的模型

public class Category : BaseFieldsTables
{
        public ICollection<Category> Categories { get; set; }
        public Category Parent { get; set; }
        public int? ParentId { get; set; }
}

我想将模型序列化为 json,这是我的控制器

    var categories =
            _efCategory.List().ToList().
                ToList().
                Select(x => new {id = x.Id, title = x.Name, children = x.Parent});

        string output = JsonConvert.SerializeObject(categories, Formatting.Indented,
                                                    new JsonSerializerSettings
                                                        {
                                                            PreserveReferencesHandling = PreserveReferencesHandling.Objects
                                                        });

        return Json(output.Replace, JsonRequestBehavior.AllowGet);

但我得到了这个结果

    "[\r\n  {\r\n    \"$id\": \"1\",\r\n    \"id\": 1,\r\n    \"title\": \"News\",\r\n    \"children\": null\r\n  },\r\n  {\r\n    \"$id\": \"2\",\r\n    \"id\": 2,\r\n    \"title\": \"2012\",\r\n    \"children\":
 {\r\n      \"$id\": \"3\",\r\n      \"Categories\": [\r\n        {\r\n          \"$id\": 

【问题讨论】:

    标签: c# asp.net-mvc json json.net


    【解决方案1】:

    这是正常的。您所看到的只是字符串的转义版本(可能直接在 Visual Studio 中)。 \r\n 相当于换行符,\" 只是逃避" 的一种方式。输出,这应该正常显示。

    【讨论】:

    • 但我想将它用于树,我收到此错误 Uncaught Invalid data type for [ { "$id": "1", "id": 2, "title": "News", "孩子": null },
    • 这意味着您正在错误地解析 JSON。您将不得不发布更多代码...... JSON 本身是正确的。
    • 我不知道为什么会这样 "$id": "13", "id": 12,
    • 您将不得不发布更多代码并更具体。
    • var categories = new CategoryMapper().MappModelToCollectionOfViewModel(_efCategory.List()) .ToList() .Select(x => new { id = x.Id, title = x.Name, children = x.父}); string output = JsonConvert.SerializeObject(categories, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects }) return Json(output, JsonRequestBehavior.AllowGet);
    猜你喜欢
    • 2012-06-04
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    相关资源
    最近更新 更多