Shagohad Shagohad - 3 months ago 22
C# Question

Web api is sending JSON object in wrong format

I am working with DevExtreme. I am trying receive JSON from web api server using ajax.

function getJSONfunction()
{
$.ajax({
url: 'http://localhost:999/api/CheckNotification?machinename=LENOVO-PC',
type: "Get",
dataType: 'json',
success: function (data) {
alert('ok');
}
})


I am expecting received from web api json object like this:

{"Result":"true"}


But problem is, web api is sending object like this:

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


And I can't see alert from getJSONfunction().

In web api "Get" function look like this:

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;
}


where "NotificationsResult" is a class

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


And my question is how can I received JSON object from api in correct format?

Answer

It seems like your result is getting serialized twice, once by you, and again by the framework.

There is no need to manually serialize your class. If it's serializable, WebApi will serialize it for you once once you return it.

You can do that following instead:

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