Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize anonymous type with literal JSON properties

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?

like image 436
ErikE Avatar asked Oct 18 '22 13:10

ErikE


1 Answers

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.

like image 199
Brian Rogers Avatar answered Oct 21 '22 09:10

Brian Rogers