英文:
@JsonFormat writes string even with NUMBER shape for a String property
问题
即使使用了NUMBER形状,为什么它还会打印带双引号的字符串?
@JsonFormat(shape = Shape.NUMBER)
private String count;
...
ObjectMapper mapper = new ObjectMapper();
Test test = new Test();
test.setCount("20");
String jsonString = mapper.writeValueAsString(test);
System.out.println(jsonString);
JSON 结果:
{
"count": "20"
}
英文:
Even with the NUMBER shape why its printing string with double quotes?
@JsonFormat(shape = Shape.NUMBER)
private String count;
...
ObjectMapper mapper = new ObjectMapper();
Test test =new Test();
test.setCount("20");
String jsonString = mapper.writeValueAsString(test);
System.out.println(jsonString);
JSON result:
{
"count" : "20"
}
答案1
得分: 1
@JsonFormat注解仅为建议,结果取决于所提供的自定义序列化程序,该程序将用于序列化给定的值。在您的情况下,将使用com.fasterxml.jackson.databind.ser.std.StringSerializer来序列化count值。该序列化程序不实现任何特殊行为,只是将值简单地写入为JSON字符串。另一方面,com.fasterxml.jackson.databind.ser.std.NumberSerializer会遵循@JsonFormat注解,如果设置为STRING格式,它将生成JSON字符串,而不是JSON数字。
因此,您总是需要检查类型序列化程序的实现,以回答诸如此类的问题。
英文:
@JsonFormat annotation is an only suggestion and result depends from given custom serialiser which will be used to serialise given value. In your case, com.fasterxml.jackson.databind.ser.std.StringSerializer will be used to serialise count value. This serialiser does not implement any special behaviour. Just simple writing value as JSON String. From other side, com.fasterxml.jackson.databind.ser.std.NumberSerializer respects @JsonFormat annotation and if you set STRING shape it will produce JSON String instead of JSON Number.
So, you always have to check type serialiser implementation to answer questions like this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论