5

How can I easily return responses that have a mix of normal objects and literal JSON strings that should be emitted inline in the JSON stream, exactly as-is without interpretation or encoding?

public JsonResult Something() {
   var literalJson = "{\"a\":1,\"b\":2}";
   return Json(new {
      result = "success",
      responseTime = DateTimeOffset.Now(),
      data = literalJson // only, don't JSON-encode this, emit it as-is
   });
}

Creating a LiteralJson class could work, with a custom Converter for it. But I'm not sure that makes the most sense.

I know how to make a custom Converter if that's a solid implementation. Are there any other ways to achieve the same goal?

ErikE
  • 48,881
  • 23
  • 151
  • 196

1 Answers1

3

If you have Json.Net installed you can use a JRaw:

public ContentResult Something()
{
    var literalJson = "{\"a\":1,\"b\":2}";

    var resp = new
    {
        result = "success",
        responseTime = DateTimeOffset.Now,
        data = new Newtonsoft.Json.Linq.JRaw(literalJson)
    };

    return Content(JsonConvert.SerializeObject(resp), "application/json", Encoding.UTF8);
}

But note that you will need to use Json.Net's serializer for this to work. That is why I changed the above code to use JsonConvert.SerializeObject and return a ContentResult rather than the using the controller's Json method like you had shown originally. The Json method uses JavaScriptSerializer internally, which doesn't know how to handle a JRaw.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • I knew there had to be another way. Why make my own `RawJson` class when a `JRaw` already exists? Thanks for the information. I do use Json.Net but was trying to stick with pure MVC just to avoid polluting possible answers—but am happy to use the Newtonsoft product in any case. – ErikE May 04 '17 at 17:12