objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
是关于在反序列化(JSON 到对象)中允许单引号,而不是根据需要序列化(对象到 JSON)。
在序列化中,问题似乎与 Jackson 1.X 的默认序列化程序有关。下面是杰克逊用来编写String
值的代码。如您所见,双引号是硬编码的,因此无法通过配置更改:
@Override
public void writeString(String text)
throws IOException, JsonGenerationException
{
_verifyValueWrite("write text value");
if (text == null) {
_writeNull();
return;
}
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = '"'; // <----------------- opening quote
_writeString(text); // <----------------- string actual value
// And finally, closing quotes
if (_outputTail >= _outputEnd) {
_flushBuffer();
}
_outputBuffer[_outputTail++] = '"'; // <----------------- closing quote
}
要实现您想要的,至少有两种选择:
1:使用正则表达式替换引号:
这是一种安全的方法,因为 Jackson 给出了"
已经转义的双引号 ( ) ( \"
)。您所要做的就是转义单引号并切换"
属性名称和值:
ObjectMapper objectMapper = new ObjectMapper();
String str = objectMapper.writeValueAsString(model);
System.out.println("Received.: "+str);
str = str.replaceAll("'", "\\\\'"); // escapes all ' (turns all ' into \')
str = str.replaceAll("(?<!\\\\)\"", "'"); // turns all "bla" into 'bla'
System.out.println("Converted: "+str);
输出:
Received.: {"x":"ab\"c","y":"x\"y'z","z":15,"b":true}
Converted: {'x':'ab\"c','y':'x\"y\'z','z':15,'b':true}
或 2:JsonSerializer
在每个String
字段上使用自定义
声明自定义序列化器:
public class SingleQuoteStringSerializer extends JsonSerializer<String> {
@Override
public void serialize(String str, JsonGenerator jGen, SerializerProvider sP)
throws IOException, JsonProcessingException {
str = str.replace("'", "\\'"); // turns all ' into \'
jGen.writeRawValue("'" + str + "'"); // write surrounded by single quote
}
}
在要单引号的字段中使用它:
public class MyModel {
@JsonSerialize(using = SingleQuoteStringSerializer.class)
private String x;
...
并照常进行(QUOTE_FIELD_NAMES == false
用于取消引用字段名称):
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
String str = objectMapper.writeValueAsString(model);
System.out.println("Received.: "+str);
输出:
Received.: {x:'ab"c',y:'x"y\'z',z:15,b:true}
注意:由于您似乎想要将 JSON 嵌入到另一个中,因此最后一种方法可能还需要转义"
s(请参阅参考资料x:'ab"c'
)。