Search code examples
javajsonspringjacksonobjectmapper

Convert Java object to json string containing a json string property already


Consider a Java object like following:

class User {

  String name;

  int age;

  String locationJson; // this is a json already

  //allArgsConstructor, getters & setters
}

so when we do,

import com.fasterxml.jackson.databind.ObjectMapper;
....

User user = new User("Max", 13, "{\"latitude\":30.0000,\"longitude\":32.0000}");

new ObjectMapper().writeValueAsString(user)), String.class);

I was expecting something like:

{
  "name": "Max",
  "age": "13",
  "locationJson": {"latitude":30.0000, "longitude":32.0000}
}

instead I got it as a json value wrapped into a double quotes and skipped by backslashes as it was double jsonized - if this is actually a verb -

{
  "name": "Max",
  "age": "13",
  "locationJson": "{\"latitude\":30.0000, \"longitude\":32.0000}"
}

Solution

  • I managed to overcome this problem by using @JsonRawValue

    From documentation https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonRawValue.html it states the following:

    Marker annotation that indicates that the annotated method or field should be serialized by including literal String value of the property as is, without quoting of characters. This can be useful for injecting values already serialized in JSON or passing javascript function definitions from server to a javascript client. Warning: the resulting JSON stream may be invalid depending on your input value.

    So by doing,

    import com.fasterxml.jackson.annotation.JsonRawValue;
    ....
    class User {
    
      String name;
    
      int age;
    
      @JsonRawValue
      String locationJson; // this is a json already
    
      //allArgsConstructor, getters & setters
    }
    

    I kinda told Jackson that this is a json value already don't do your job here so same code in post generated the correct json

    {
      "name": "Max",
      "age": "13",
      "locationJson": {"latitude":30.0000, "longitude":32.0000}
    }