FasterXML / jackson-annotations

Core annotations (annotations that only depend on jackson-core) for Jackson data processor
https://github.com/FasterXML/jackson
Apache License 2.0
1.03k stars 330 forks source link

JsonProperty does not work as expected #110

Closed xiaoshuang-lu closed 7 years ago

xiaoshuang-lu commented 7 years ago
public class Endpoint {
    @JsonProperty("serviceName")
    private String serviceName;

    @JsonProperty("ipv4")
    private String ipV4Address;

    public String getServiceName() {
        return this.serviceName;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    public String getIPV4Address() {
        return this.ipV4Address;
    }

    public void setIPV4Address(String ipV4Address) {
        this.ipV4Address = ipV4Address;
    }

    public static void main(String[] stringArray) {
        String serviceName = "serviceName";

        String ipV4Address = "localhost";

        Endpoint endpoint = new Endpoint();

        endpoint.setServiceName(serviceName);

        endpoint.setIPV4Address(ipV4Address);

        ObjectMapper objectMapper = new ObjectMapper();

        try {
            String json = objectMapper.writeValueAsString(endpoint);

            System.out.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

expected output: {"serviceName":"serviceName","ipv4":"localhost"} actual output: {"ipv4Address":"localhost","serviceName":"serviceName","ipv4":"localhost"}

affects version: 2.8.5

cowtowncoder commented 7 years ago

This is because getIPV4Address and setIPV4Address would map to ipv4Address, which is different from field name of ipV4Address (capitalization differs in V). If you want that property to be renamed as ipv4 please move @JsonProperty to getter or setter method; there is no point in adding it to private field that is not visible anyway.

xiaoshuang-lu commented 7 years ago

All right. Thank you, @cowtowncoder.