简体   繁体   中英

Converting any string to JSON format in C#

I am using GET method (MCV4 / WEB-API/ VS 2010).

I want to return a response string in json format.

I have a string (any string) and want to convert it to json to be return as response).

How can I convert any string to JSON format:

string s = "{\"one\":\"a\", \"two\": \"2\"}";
Request.CreateResponse(HttpStatusCode.OK, <what shall i put here in order to return json of string s>);

Can I do something like this? :

string s = "{\"one\":\"a\", \"two\": \"2\"}";
Request.CreateResponse(HttpStatusCode.OK, s, "application/json");

I need to convert string, because I am using 3rd party tool, that send me string (and not json object). I don't understand what wrong, because json represented actually a long string - it just called json.

I don't know whether the response add " sign, because I am cheking that on advanced rest client plugin for chrome, and I see " sign before and after the string. Nevertheless, string I pass, shall be with " sign before and after.

Thanks :)

Generally you don't convert the object you plan to return to a particular format with Web API. The server will return the data in the requested format if it knows how, based on content negotiation. So your function signature should return a string, and Web API will take care of converting to XML or JSON as appropriate.

See Web API Content Negotiation .

Update, example function:

public string GetString()
     {
     string s="Hello, world!";
     return s;
     }

or

public HttpResponseMessage GetString()
    {
    string s="Hello, world!";
    return Request.CreateResponse(HttpStatusCode.Ok, s);
    }

If you want to return a dictionary, then something like this:

public Dictionary<string,string> GetDict()
    {
    var dict=new Dictionary<string,string>();
    dict.Add("one", "a");
    dict.Add("two", "2");
    return dict;
    }

or

public HttpResponseMessage GetDict()
    {
    var dict=new Dictionary<string,string>();
    dict.Add("one", "a");
    dict.Add("two", "2");
    return Request.CreateResponse(HttpStatusCode.Ok, dict);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM