0

This question is different from the one suggested by the mod. because I am returning a string and not an object here.

I am attempting to send a json string back to the client. However it is invalid (the formatting is incorrect) any suggestions on how I can fix this ?

This is the server side

    [HttpGet]
    public string foo()
    {
        Dictionary<string, string> response = new Dictionary<string, string>();
        response["itemID"] = "ABC";
        return JsonConvert.SerializeObject(response);
    }

and on the client side I am doing this

    using (WebClient client = new WebClient())
    {
       string clientResponse = client.DownloadString(url);
       Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(clientResponse);

    }

clientRepsonse is apparently not properly formatted json its like this (shown below). Thats why it cannot be de-searialized

"{\"itemID\":\"ABC\"}"

Any suggestions on how I can fix this. In the locals in visual studio it looks like this "\"{\\\"itemID\\\":\\\"ABC\\\"}\"" And in preview it looks like this "{\"itemID\":\"ABC\"}"

MistyD
  • 16,373
  • 40
  • 138
  • 240
  • 1
    Are the escape characters included in the json string, or is that just how it's being displayed by visual studio? `"{\"itemID\":\"ABC\"}"` as a string deserializes to a `Dictionary` just fine as far as I can tell. – Jonathon Chase Dec 18 '19 at 22:12
  • Let me post what visual studio shows – MistyD Dec 18 '19 at 22:13
  • What error are you getting? Or you just looked at the escaped string? I have tried this `var dc=JsonConvert.DeserializeObject>("{\"One\":\"A\",\"Two\":\"B\",\"Three\":\"C\"}");` and it works fine. – TheVillageIdiot Dec 18 '19 at 22:14
  • I am going to post the exact result that i see, I am running it now – MistyD Dec 18 '19 at 22:15
  • @JonathonChase this is how its showing up `"{\"itemID\":\"ABC\"}"` in visual studio. When I attempt to deserailize it to a dictionary it fails. I am not sure why its failing. The string looks fine to me. But in the locals it looks like this `"\"{\\\"itemID\\\":\\\"ABC\\\"}\"" ` – MistyD Dec 18 '19 at 22:21
  • You should return an `ActionResult` like suggested in the duplicate. Then you'll be able to deserialise into the Dictionary. The string produced by the controller is not valid representation of json – haldo Dec 19 '19 at 00:11
  • Okay, you are returning JSON string which is getting escaped again. Read the referred question and return JSON instead of a string. – TheVillageIdiot Dec 19 '19 at 01:28

1 Answers1

1

Try adding [Produces("application/json")] to your controller level.

[Produces("application/json")]
public class MyController : ControllerBase
Mohamed Farouk
  • 1,089
  • 5
  • 10