Java JsonValue-class And Method Code Example

Here is an example of how to use the JsonValue annotation from the Apache Commons IO library to serialize a field to a specific JSON value:

import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Example {
    public static class Person {
        private String name;
        private Gender gender;
        // getters and setters

    public static enum Gender {

        private String value;

        Gender(String value) {
            this.value = value;

        public String getValue() {
            return value;

    public static void main(String[] args) throws Exception {
        Person person = new Person();
        person.setName("John Doe");

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(person);

This will output:

{"name":"John Doe","gender":"m"}

As you can see, the gender field is serialized to the specific JSON value returned by the getValue() method, instead of the default string representation of the Gender enum.

Note: This is using the Jackson JSON library to serialize the POJO to JSON. You need to have the jackson-databind jar in your classpath for this to work.

Please note that JsonValue is not a part of Apache Commons IO library. It's from Jackson JSON library.