Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to globally define the naming convention with Jackson

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.

like image 382
dyesdyes Avatar asked Aug 17 '16 06:08

dyesdyes


People also ask

What does JsonPOJOBuilder do?

The @JsonPOJOBuilder annotation is used to configure a builder class to customize deserialization of a JSON document to recover POJOs when the naming convention is different from the default. The names of the bean's properties are different from those of the fields in JSON string.

What is JsonIdentityInfo?

The @JsonIdentityInfo annotation is used when an object has a parent-child relationship in the Jackson library. The @JsonIdentityInfo annotation is used to indicate the object identity during the serialization and deserialization process.

What is Jackson mixin?

Jackson mixins is a mechanism to add Jackson annotations to classes without modifying the actual class. It was created for those cases where we can't modify a class such as when working with third-party classes. We can use any Jackson annotation but we don't add them directly to the class.


2 Answers

Not sure how to do this globally but here's a way to do it at the JSON object level and not per each individual property:

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

would yield json:

{
    "my_bean_name": "Sth"
    //...
}
like image 125
dimitrisli Avatar answered Oct 19 '22 20:10

dimitrisli


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;
    }
}
like image 5
dyesdyes Avatar answered Oct 19 '22 22:10

dyesdyes