0

I am trying to return a JSON for the Web API I am building. The API returns the JSON with \ slashes that makes difficult for my other application to consume this API.

 "   {\"@odata.context\":\"https://science.com/odata/$metadata#EMPLOYEE\",\"value\":[{\"Id\":5000004,\"Name\":\"Account\"}]}"

But I am expecting a response like

{
"@odata.context": "https://science.com/odata/$metadata#EMPLOYEE",
"value": [
    {
        "Id": 5000004,
        "Name": "Account"
    }]}

Below is the code for my Web API

public async Task<string> GetEmployee(string instance)
{
    .....
    EmployeeDTO.RootObject returnObj = new EmployeeDTO.RootObject();
    var responsedata = "";
    try
    {
        using (var client_Core = new HttpClient())
        {
            ....
            string core_URL = BaseURL_Core+URL_instance;
            var response = client_Core.GetAsync(core_URL).Result;

            responsedata = await response.Content.ReadAsStringAsync();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return responsedata;
}

I have also added the Content type in the WebAPIConfig file like below

var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");

config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

But I am still getting the JSON with the slashes

1
  • I think you're confusing what debug output is showing you for the actual contents of the string. Where are you seeing the string with all the \s? Commented Aug 20, 2018 at 20:03

1 Answer 1

2
responsedata = await response.Content.ReadAsStringAsync();

Above code returns string and you return the same response back. As the result, it is not well-formed JSON you expected.

If you want to return proper JSON, you'll need to convert string to JSON before returning it.

public async Task<Data> GetEmployee(string instance)
{
    string responsedata = "   {\"@odata.context\":\"https://science.com/odata/$metadata#EMPLOYEE\",\"value\":[{\"Id\":5000004,\"Name\":\"Account\"}]}";

    return JsonConvert.DeserializeObject<Data>(responsedata);
}

public class Data
{
    [JsonProperty("@odata.context")]
    public string ODataContext { get; set; }

    public Value[] Value { get; set; }
}

public class Value
{
    public int Id { get; set; }
    public string Name { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.