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 {
        MALE("m"),
        FEMALE("f");

        private String value;

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

        @JsonValue
        public String getValue() {
            return value;
        }
    }

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

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(person);
        System.out.println(json);
    }
}

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.