I'm migrating an ASP.NET Core 2 application to ASP.NET Core 3. My controllers need to return objects that have a property which is already a JSON string, so it looks something like this:
public class Thing {
public int Id { get; set; }
public string Name { get; set; }
public string Data { get; set; } // JSON Data
}
var thing = new Thing
{
Id = 1,
Name = "Thing",
Data = "{\"key\":\"value\"}"
};
Thing
should be serialized so that the Data
property is not a string, but part of the JSON object. Like this:
{
"id": 1,
"name": "Thing",
"data": {
"key": "value"
}
}
In .NET Core 2 and Newtonsoft.Json
I used JRaw
as the type for Data
, so the serializer knew that the property is already serialized as JSON and didn't try to represent it as a string.
.NET Core 3 uses System.Text.Json
, which is incompatible with JRaw
. Is there an equivalent that does the same thing? I was able to use JsonElement
as the type for Data
and convert the string with JsonDocument.Parse(jsonString).RootElement
. This produces the desired result, but I'd like to avoid an unnecessary deserialize+serialize step, since the data object may be relatively big.