我正在与DevExtreme合作。我正在尝试使用Ajax从Web API服务器接收JSON。
function getJSONfunction()
{
$.ajax({
url: 'http://localhost:999/api/CheckNotification?machinename=LENOVO-PC',
type: "Get",
dataType: 'json',
success: function (data) {
alert('ok');
}
})
我期望从Web api json对象收到这样的消息:
{"Result":"true"}
但是问题是,Web API正在发送这样的对象:
"{\"Result\":\"true\"}"
而且我看不到来自getJSONfunction()的警报。
在网络API中,“获取”功能如下所示:
public string Get(string machineName)
{
int NotificationsNumber = NotificationsFunctions.CheckForNotifications(machineName);
NotificationsResult result = new NotificationsResult();
if(NotificationsNumber > 0)
{
result.Result = "true";
}else
{
result.Result = "false";
}
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(result);
return json;
}
其中“ NotificationsResult”是一个类
public class NotificationsResult
{
public string Result { get; set; }
}
我的问题是如何从api接收正确格式的JSON对象?
看来您的结果被序列化了两次,一次是由您,另一次是由框架。
无需手动序列化您的类。如果它是可序列化的,WebApi将在您返回它后为您序列化一次。
您可以改为执行以下操作:
public NotificationsResult Get(string machineName)
{
int NotificationsNumber = NotificationsFunctions.CheckForNotifications(machineName);
return new NotificationsResult
{
Result = NotificationsNumber > 0 ? "true" : "false";
};
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句