【发布时间】: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