[英]Jackson serialize POJO to JS Object
class Foo {
String name = "Bar";
}
Serialising the above object using ObjectMapper().convertValue(foo, JsonNode::class)
will return JSON object as:使用ObjectMapper().convertValue(foo, JsonNode::class)
序列化上述对象将返回 JSON 对象:
{
"name": "Bar"
}
my desired result however is:然而,我想要的结果是:
{
name: "Bar"
}
I have tried a custom serialiser but it always writes keys as strings.我尝试过自定义序列化程序,但它总是将键写为字符串。 Is there a way to serialise my POJO in this format using Jackson or any of it's annotation to avoid a substituting chars or building the string my self.有没有办法使用 Jackson 或它的任何注释以这种格式序列化我的 POJO,以避免替换字符或构建我自己的字符串。
Beside the fact that your "JSON" will not be valid anymore you can disable JsonGenerator.Feature.QUOTE_FIELD_NAMES
in your ObjectMapper
.除了您的“JSON”不再有效这一事实之外,您还可以在ObjectMapper
禁用JsonGenerator.Feature.QUOTE_FIELD_NAMES
。
ObjectMapper mapper = new ObjectMapper()
.disable(JsonGenerator.Feature.QUOTE_FIELD_NAMES);
The result of mapper.writeValueAsString(new Foo())
will be: mapper.writeValueAsString(new Foo())
将是:
{name:"Bar"}
To enable pretty print you can use either:要启用漂亮的打印,您可以使用:
ObjectMapper mapper = new ObjectMapper()
.disable(JsonGenerator.Feature.QUOTE_FIELD_NAMES)
.enable(SerializationFeature.INDENT_OUTPUT);
Or use this in the output step:或者在输出步骤中使用它:
String result = mapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(new Foo());
The result in both cases will be:两种情况下的结果都是:
{
name : "Bar"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.