mercredi 24 février 2016

How can I find the JSON key of a field (jackson)

I have the following promlem. I export my user object as usualwith the jackson.databind.ObjectMapper and that works fine ({"address":{"village":"NY"},"prename":"Joe"}).

Now I have to get the key (address and prename) with java reflection. If the field has the annotation @JsonPropertie there is no problem to get this key. But this annotation isn't pressent on all fields (for example the m_address field).

At How does the Jackson mapper know what field in each Json object to assign to a class object? I read that the ObjectMapper try to call the getter or so.

But I have no clue how I can find the right getter to my field.

I know that this isn't probably the most beautifull way to solve my problem but I haven't found any method on the ObjectMapper like "mapper.getJSONKeyByName(field)". If something like that exist even better. :)

So my question is is there a way to find the right getter to a field and does something like "mapper.getJSONKeyByName(field)" exist on the ObjectMapper?

Thanks for your answer.

Main.java

public static void main(String[] args) throws Exception {
    ObjectMapper mapper = new ObjectMapper();   

    // Object to JSON as usual
    mapper.writeValue(System.out, new User("Joe", new Address("NY"))); // {"address":{"village":"NY"},"prename":"Joe"}


    // Lookup with reflection
    for (Field field : User.class.getDeclaredFields()) {
        field.setAccessible(true);
        try {
            if (field.isAnnotationPresent(JsonProperty.class)) {
                System.out.println("JSON-Key with annotation: " + field.getAnnotation(JsonProperty.class).value()); // JSON-Key with annotation: prename
            } else {
                //TODO do something to get "JSON-Key without annotation: address
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

User.java

public class User implements Serializable{

@JsonProperty(value="prename")
private String m_name;

private Address m_address;

public User(String name, Address a) {
    m_name = name;
    m_address = a;
}

@JsonIgnore
public String getName() {
    return m_name;
}

public void setName(String name) {
    m_name = name;
}

public Address getAddress() {
    return m_address;
}

public void setAddress(Address address) {
    m_address = address;
}
}





Aucun commentaire:

Enregistrer un commentaire