我只想向浏览器返回一个 JSON。
这是现在返回的内容——它是 JSON,但在字符串中。如何只返回一个 JSON?
这是我的代码:
namespace ...Controllers
{
public class NotificationsController : ApiController
{
public string getNotifications(int id)
{
var bo = new HomeBO();
var list = bo.GetNotificationsForUser(id);
var notificationTreeNodes = (from GBLNotifications n in list
where n.NotificationCount != 0
select new NotificationTreeNode(n)).ToList();
List<Node> lOfNodes = new List<Node>();
foreach (var notificationTreeNode in notificationTreeNodes)
{
Node nd = new Node();
nd.notificationType = notificationTreeNode.NotificationNode.NotificationType + " " + "(" + notificationTreeNode.NotificationNode.NotificationCount + ")";
var notificationList = bo.GetNotificationsForUser(id, notificationTreeNode.NotificationNode.NotificationTypeId).Cast<GBLNotifications>().ToList();
List<string> notificationDescriptions = new List<string>();
foreach (var item in notificationList)
{
notificationDescriptions.Add(item.NotificationDescription);
}
nd.notifications = notificationDescriptions;
lOfNodes.Add(nd);
}
var oSerializer = new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(lOfNodes);
return sJSON;
}
}
public class Node
{
public string notificationType
{
get;
set;
}
public List<string> notifications
{
get;
set;
}
}
}
如果我尝试使用此 Controller 的 URL 执行 GET,Fiddler 不会在 JSON 下显示任何内容。
有人知道这里的问题是什么吗?
最佳答案
因为你返回的是 JSON:
var oSerializer = new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(lOfNodes);
return sJSON;
你不应该这样做,而是返回 lOfNodes
(并将返回值更改为 List<Node>
)并依赖内置的内容协商。
Web API 将根据 Accept
返回 XML 或 JSON header 。如果您需要其他格式,您可以轻松编写自己的格式化程序。
编辑:
由于您在使用 Kendo UI 时遇到了一些问题(我不知道请求是如何发出的),它可能有助于显式删除 XML 格式化程序。参见 this post举个例子。
关于c# - 为什么我的 API 在 XML 节点内返回一个 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17931909/