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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With