如何使用Jackson全局定义命名约定(how to globally define the naming convention with Jackson)

我和杰克逊一起使用Spring。 我有几个像这样的方法:

@RequestMapping(value = "/myURL", method = RequestMethod.GET) public @ResponseBody Foo getFoo() { // get foo return foo; }

序列化的Foo类很大,有很多成员。 序列化没问题,使用注释或自定义序列化程序。

我唯一无法弄清楚的是如何定义命名约定。 我想对所有序列化使用snake_case。

那么如何全局定义序列化的命名约定?

如果不可能,那么本地解决方案就必须这样做。

I'm using Jackson with Spring. I have a few methods like this:

@RequestMapping(value = "/myURL", method = RequestMethod.GET) public @ResponseBody Foo getFoo() { // get foo return foo; }

The class Foo that's serialized is quite big and has many members. The serialization is ok, using annotation or custom serializer.

The only thing I can't figure out is how to define the naming convention. I would like to use snake_case for all the serializations.

So how do I define globally the naming convention for the serialization?

If it's not possible, then a local solution will have to do then.

最满意答案

不确定如何在全局范围内执行此操作,但这是在JSON对象级别而不是每个单独的属性执行此操作的方法:

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) public class Foo { private String myBeanName; //... }

会产生json:

{ "my_bean_name": "Sth" //... }

Actually, there was a really simple answer:

@Bean public Jackson2ObjectMapperBuilder jacksonBuilder() { Jackson2ObjectMapperBuilder b = new Jackson2ObjectMapperBuilder(); b.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); return b; }

I added it in my main like so:

@SpringBootApplication public class Application { public static void main(String [] args) { SpringApplication.run(Application.class, args); } @Bean public Jackson2ObjectMapperBuilder jacksonBuilder() { Jackson2ObjectMapperBuilder b = new Jackson2ObjectMapperBuilder(); b.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); return b; } }

更多推荐