c# - 为什么我的 API 在 XML 节点内返回一个 JSON?

标签 c# json asp.net-web-api fiddler

我只想向浏览器返回一个 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/

相关文章:

c# - 从 webapi 中的 async DelegatingHandler 读取异步响应内容时出现死锁

asp.net-mvc - 用户身份如何?应用程序生命周期中的主体集

api - 当您可以实现版本控制时,为什么开发人员对发布 API 如此珍贵?

javascript - 为什么是 myPlants[1]? JSON

javascript - Node API等待外部数据

javascript - Angular/Typescript——通过示例解释接口(interface)的好处

c# - 无法从 gridview 内的 templateField 中的文本框获取值

c# - 运算符 == 不能应用于 C# 中的泛型类型吗?

c# - 访问公共(public)保管箱文件夹中的所有保管箱图像

javascript - 在 JavaScript 中分析 JSON 数据