20

For example, I want to generate a json string for ng-style:

<th ng-style="{width:247}" data-field="code">Code</th>

But with jackson, the result is:

<th ng-style="{&quot;width&quot;:247}" data-field="code">Code</th>

It's not easy to read.

So I want jackson to generate the json string with single quote or no quotes. Is it possible to do this?

Freewind
  • 193,756
  • 157
  • 432
  • 708

3 Answers3

39

If you have control over the ObjectMapper instance, then configure it to handle and generate JSON the way you want:

final ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
Perception
  • 79,279
  • 19
  • 185
  • 195
4
JsonGenerator.Feature.QUOTE_FIELD_NAMES

is deprecated, you can use this instead:

mapper.configure(JsonWriteFeature.QUOTE_FIELD_NAMES.mappedFeature(), false);
mapper.configure(JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES.mappedFeature(), true);

Note that JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES is not deprecated (as of now), the corresponding JsonReadFeature is mentioned here just for completeness.

Remigius Stalder
  • 1,921
  • 2
  • 26
  • 31
-7

The simplest and the best option is to use regular expression and update the string value.

The sample code is as listed below.

partNumberList=partNumberList.replaceAll(":", ":\"").replaceAll("}", "\"}");

The complete code is as shown below

public static void main(String[] args) throws JsonParseException, JsonMappingException, 
    IOException {
    TestJack obj = new TestJack();
    //var jsonString ='{"it":"Stati Uniti d'America"}';
    //            jsonString =jsonString.replace("'", "\\\\u0027")
    ObjectMapper mapper = new ObjectMapper();
    String partNumberList = "[{productId:AS101R}, {productId:09902007}, {productId:09902002}, {productId:09902005}]";
    partNumberList = partNumberList.replaceAll(":", ":\"").replaceAll("}", "\"}");
    System.out.println(partNumberList);
    mapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    List<ProductDto> jsonToPersonList = null;
    jsonToPersonList = mapper.readValue(partNumberList, new TypeReference<List<ProductDto>>() {
    });
    System.out.println(jsonToPersonList);
}
James Fenwick
  • 2,190
  • 1
  • 20
  • 30
Deepak
  • 1
  • You should avoid this solution and doing things like it - all the escape sequences will be treated literally - you could possibly end up with an illegal value if there is an escaped double quote or contained single quote - YIKES! – Yoshiya Mar 16 '19 at 12:28