【问题标题】:AngularJS doesn't handle JSON referenceAngularJS 不处理 JSON 引用
【发布时间】:2014-02-12 18:49:44
【问题描述】:

我正在创建一个小网站来管理食谱。我有一个 MVC web api 服务器端和一个 angular js 前端。

现在我的 MVC web api 将 JSON 序列化为(干净易读,感谢 chrome 插件 JSONView)

[
{
$id: "1",
Name: "Spaghetti",
CookTime: "00:30:00",
Servings: 2,
CategoryId: 1,
Category: {
$id: "2",
Name: "Pasta",
Recipes: [
{
$ref: "1"
},
{
$id: "3",
Name: "Recipe 2",
CookTime: "01:20:00",
Servings: 2,
CategoryId: 1,
Category: {
$ref: "2"
}
Id: 2
}
],
Id: 1
}
Id: 1
},
{
$ref: "3"
}
]

但在我的页面上,我只得到列表中的第一个对象和一个空的第二个 tr 标记。 有没有办法让 AngularJS 理解 $ref 参考?还是我应该修改我的 web api 配置?

config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(
    config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"));

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

config.Formatters.Remove(config.Formatters.XmlFormatter);

- 更新

上面的 json 是一个 chrome 扩展的漂亮表示。以下是我从我的服务中获得的原始数据(并使用 JSONLint 格式化,表示它是有效的 JSON):

[
    {
        "$id": "1",
        "Name": "Spaghetti",
        "CookTime": "00:30:00",
        "Servings": 2,
        "CategoryId": 1,
        "Category": {
            "$id": "2",
            "Name": "Pasta",
            "Recipes": [
                {
                    "$ref": "1"
                },
                {
                    "$id": "3",
                    "Name": "Recipe 2",
                    "CookTime": "01:20:00",
                    "Servings": 2,
                    "CategoryId": 1,
                    "Category": {
                        "$ref": "2"
                    }
                    "Id": 2
                }
            ],
            "Id": 1
        }
        "Id": 1
    },
    {
        "$ref": "3"
    }
]

【问题讨论】:

  • 你的 JSON 搞砸了——这真的是你从序列化中得到的吗?
  • JSON 没有被字符串化。

标签: javascript asp.net-mvc json angularjs model-view-controller


【解决方案1】:

您的 JSON 无效,这意味着问题出在 API 端。

Category: {
  $ref: "2"
}
Id: 2
...
  ],
  Id: 1
}
Id: 1

Id: 2Id: 1 之前必须有一个逗号才能成功解析。

【讨论】:

    【解决方案2】:

    来自 api 的人已经更新了他们的代码,因此现在不再出现循环。这解决了我的问题。

    还是谢谢! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      相关资源
      最近更新 更多