Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return serialized JSON string, without further serialization from ASP.Net Core API

This question is similar to Return "raw" json in ASP.NET Core 2.0 Web Api but slightly more complicated.

I have a mixed content, some class like:

public class ResponseModel
{
    public Guid Id { get; set; }
    public DateTime TimesStamp { get; set; }

    // this is actually JSON serialized data, 
    // which the function just passes through and doesn't need to understand
    public string Data { get; set; }
}

Currently, a response would contain the Id and TimeStamp serialized correctly and Data would just be a string which would need to be deserialized one more time.

I'd instead want Data to be just pointing to the "Raw" json string, which I set it to, without further escaping it.

We don't make use of content negotiation, we only support JSON request and response, so this would be fine.

I know that I could deserialize the json string into a dynamic object and that would work, but why should the string be deserialized just to be serialized again?

So what I would want is something like

public class ResponseModel
{
    public Guid Id { get; set; }
    public DateTime TimesStamp { get; set; }

    public object Data { get; set; }
}

but without the need to spend unnecessary time to deserialize and again serialize the content of the json string.

like image 263
peter Avatar asked May 31 '26 22:05

peter


1 Answers

Not possible. If it's a string, you know it's JSON, but the serializer has no way of knowing that. However, even if it could somehow determine that it's a JSON string, it would still need to internally deserialize it so it could work it into the rest of the object, before serializing the whole thing - effectively no different than doing it yourself.

like image 110
Chris Pratt Avatar answered Jun 04 '26 10:06

Chris Pratt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!