Home > OS >  Avoid re-serializing of a json string
Avoid re-serializing of a json string

Time:09-13

Is there a way to selectively exclude a field from re-serialization, if it already contains a valid json string?

Here is what I am attempting.

First, I define a class of the result row I recieve from my database.

public class objectToSerialize
{
    public string identifier { get; set; }
    public string jsonPayload { get; set; }

    public objectToSerialize()
    {
        identifier = String.Empty;
        jsonPayload = String.Empty;
    }
}

Then I run my query and add all the results to a list.

List<objectToSerialize> listOfobjectToSerialize = new List<objectToSerialize>();
[...]

while(SqlDataReader.Read())
{
   [...]
   listOfobjectToSerialize.add(objectToSerialize)
}

Finally, I return my list as an APS.NET OkObjectResult, which serializes the list to JSON by default.

[...]
return (ActionResult)new OkObjectResult(listOfobjectToSerialize);

The jsonPayload already contains a json string, that should not be re-serialized again when returning the result.
So far I have deserialized the jsonPayload to an object, which was then serialized fine, but I would like to avoid that unnessesary step.
I have tried using the field attributes [JsonIgnore] and [NonSerialized()] but they remove the field from the result altogether.

Is there a way to include the jsonPayload string as-is?

Here is an example:

objectToSerialize.identifier = 123;
objectToSerialize.jsonPayload = @"
   {
      "ThisIsAKey" : "ThisIsAValue"
   }"

Desired output:

{
   "identifier" : 123,
   "jsonPayload" : {
      "ThisIsAKey" : "ThisIsAValue"
   }
}

Actual output:

{
   "identifier" : 123,
   "jsonPayload" : "{
      \"ThisIsAKey\" : \"ThisIsAValue\"
   }"
}

So far I am trying to write my own custom JsonConverter.

CodePudding user response:

this will not be even compiled

objectToSerialize.jsonPayload = @"
   {
      "ThisIsAKey" : "ThisIsAValue"
   }"

if you want Desired output

objectToSerialize.jsonPayload = new
   {
      ThisIsAKey = "ThisIsAValue"
   };

but as I guess your jsonPayload is a string , so you can only do this

objectToSerialize.jsonPayload = @"{
      ""ThisIsAKey"" : ""ThisIsAValue"" 
      }";

leave like this, otherwise you are just looking for a trouble, you will not be able to deserialize jsonPayload to string when you get your response.

CodePudding user response:

If it is already the JSON, we could give a try to plain/text as the content type of the response.

May be,

Request.Content = "text/plain";

return Content(alreadyCreatedJson);

  • Related