Web api 正在以错误的格式发送 JSON 对象

Web api is sending JSON object in wrong format

我正在与 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"}

但问题是,网络 api 正在发送这样的对象:

"{\"Result\":\"true\"}"

而且我看不到来自 getJSONfunction() 的警报。

在网络中 api "Get" 函数如下所示:

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" 是 class

public class NotificationsResult
{
    public string Result { get; set; }
}

我的问题是如何以正确的格式从 api 接收到 JSON 对象?

在客户端使用 jQuery.parseJSON(json) 你可能会得到你预期的结果

您的结果似乎被序列化了两次,一次由您序列化,另一次由框架序列化。

无需手动序列化您的class。如果它是可序列化的,WebApi 将在您 return 之后为您序列化一次。

您可以改为执行以下操作:

public NotificationsResult Get(string machineName)
{
    int NotificationsNumber = NotificationsFunctions.CheckForNotifications(machineName);
    return new NotificationsResult
    {
        Result = NotificationsNumber > 0 ? "true" : "false";             
    };
}

只需使用 JsonResult

public JsonResult Get(string machineName)
    {
        int NotificationsNumber = NotificationsFunctions.CheckForNotifications(machineName);
        NotificationsResult result = new NotificationsResult();
        if(NotificationsNumber > 0)
        {
            result.Result = "true";
        }else
        {
            result.Result = "false";
        }

        return Json(result);
    }