Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let jackson generate json string using single quote or no quotes?

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?

like image 770
Freewind Avatar asked Dec 23 '12 11:12

Freewind


People also ask

Can JSON strings use single quotes?

Strings in JSON are specified using double quotes, i.e., " . If the strings are enclosed using single quotes, then the JSON is an invalid JSON .

Should I use single or double quotes in JSON?

Answer #1:JSON requires double quotes for its strings.

Can JSON key be without quotes?

JavaScript object literals do not require quotes around a key name if the key is a valid identifier and not a reserved word. However, JSON always requires quotes around key names.


2 Answers

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);
like image 185
Perception Avatar answered Sep 20 '22 09:09

Perception


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.

like image 32
Remigius Stalder Avatar answered Sep 17 '22 09:09

Remigius Stalder