C# 为什么我的API在XML节点内返回JSON?
我只想将JSON返回到浏览器 这就是现在返回的内容——它是JSON,但在字符串中。如何仅返回一个JSON 这是我的代码:C# 为什么我的API在XML节点内返回JSON?,c#,json,asp.net-web-api,fiddler,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();
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;
}
}
}
如果我尝试使用该控制器的URL进行GET,Fiddler不会在JSON下显示任何内容
有人知道这里有什么问题吗?因为您返回了JSON:
var oSerializer = new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(lOfNodes);
return sJSON;
与其这样做,您应该只返回lOfNodes并将返回值更改为List,并依赖内置的内容协商
Web API将根据Accept标头返回XML或JSON。如果需要其他格式,可以轻松编写自己的格式化程序
编辑:
由于您在KendoUI上遇到了一些问题,我不知道请求是如何发出的,删除XML格式化程序可能会有所帮助。请参阅以获取示例。因为您返回了JSON:
var oSerializer = new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(lOfNodes);
return sJSON;
与其这样做,您应该只返回lOfNodes并将返回值更改为List,并依赖内置的内容协商
Web API将根据Accept标头返回XML或JSON。如果需要其他格式,可以轻松编写自己的格式化程序
编辑:
由于您在KendoUI上遇到了一些问题,我不知道请求是如何发出的,删除XML格式化程序可能会有所帮助。请参见示例。问题是我需要返回一个JSON,以便在我的KendoUI TreeView中使用它…Web API将根据Accept标头为您处理此问题。我将其还原为您所要求的内容。但是我很难让剑道ui正常工作。。。你擅长吗?我可以显示父项,但不能显示子项:我熟悉Web API,但不熟悉剑道UI。问题是我需要返回JSON,以便在我的剑道树视图中使用它…Web API将根据Accept标头为您处理此问题。我将其还原为我所拥有的,这正是您告诉我的。但是我很难让剑道ui正常工作。。。你擅长吗?我能够显示父项,但不能显示子项:我熟悉Web API,但不熟悉剑道UI。