Search code examples
javajsonjacksonjackson-databindobjectmapper

Remove unescape characters and format json


How can I transform this:

"parameters" : [ "{name:\"xx\", value:\"45\",typRef:\"FE\",unit:\"grad\"}" ],

to this:

"parameters" : [ {
        "name" : "xx",
        "value" : "45",
        "typRef" : "FE",      
        "unit" : "grad"
        }]

I use the objectMapper to write as String

public class ParameterClass 
   {
      @NonNull private final String name;
      @JsonInclude(JsonInclude.Include.NON_NULL) private final String value;
      @JsonInclude(JsonInclude.Include.NON_NULL) private final typRef;
      @JsonInclude(JsonInclude.Include.NON_NULL) private final String unit;

      private ParameterClass (@NonNull String name, String value, String typRef, String unit)
      {
         this.name = name;
         this.value = value;
         this.typRef = typRef;
         this.unit = unit;
      }

The method to build a json

buildAsJson(String name, String unit, ...) {
ParameterClass parameter = new ParameterClass(name, unit, ..);
return objectMapper.writeValueAsString(parameter);
}

I collect all into a list:

List<String> parameters = List.of(buildAsJson("xx", "45", ...), buildAsJson(...)) 

Solution

  • Just store the string parameter, then read that JSON string with objectMapper.readTree(...). It will convert the JSON string to valid JSON format if the JSON string is valid.

    JsonNode buildAsJson(String name, String unit, ...) {
      ParameterClass parameter = new ParameterClass(name, unit, ..);
      String parameter = objectMapper.writeValueAsString(parameter);
      return objectMapper.readTree(parameter);
    }