@JsonFormat对于String属性,即使使用NUMBER格式,也会写入字符串

huangapple go评论71阅读模式
英文:

@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.

huangapple
  • 本文由 发表于 2020年8月28日 02:50:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63622458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定