Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json string gets escaped in web-api

we have JSON configuration data stored in a database. i need to fetch this JSON data and return it, as it is, to the browser via asp.net web-api:

public class ConfigurationController : ApiController
{
    public string Get(string configId)
    {
        // Get json from database
        // when i return the fetched json it get's escaped
    }
}

The value that i return gets escaped. how do i simply return the string as it is? I really don't want to populate an object that gets serialized to JSON.

like image 280
sundown Avatar asked Mar 27 '14 13:03

sundown


People also ask

Does JSON need to be escaped?

JSON is pretty liberal: The only characters you must escape are \ , " , and control codes (anything less than U+0020).

What is escaping in JSON?

Escapes or unescapes a JSON string removing traces of offending characters that could prevent parsing. The following characters are reserved in JSON and must be properly escaped to be used in strings: Backspace is replaced with \b. Form feed is replaced with \f.

Can we return JSON from Web API?

By default, Web API produces XML but if there is need for JSON, given syntax will do it. Open WebApiConfig. cs file in solution and add mentioned line in it as shown in example.


2 Answers

You can return a HttpResponseMessage from the ApiController which allows you to basically return a string value.

e.g.

public HttpResponseMessage Get()
{
    return new HttpResponseMessage() { 
        Content = new StringContent("Hello World", System.Text.Encoding.UTF8, "application/json") 
    };
}

What you would want to do is just pass the json string as the StringContent.

like image 184
Tim B James Avatar answered Oct 19 '22 03:10

Tim B James


The accepted answer is slightly off. The correct version is:

public HttpResponseMessage Get()
{
    return new HttpResponseMessage() { 
        Content = new StringContent("Hello World", System.Text.Encoding.UTF8, "application/json") 
    };
}

It's the StringContent function that correctly removes the escaping. Without the application/json media type, tools like postman won't correctly display the "pretty" version of the result.

like image 7
wilsotc Avatar answered Oct 19 '22 02:10

wilsotc