mercredi 24 février 2016

Get JSON key of Field via Java Reflection

I have the folllowing problem. I want to get the "json-name" ("adr" if the @JsonProperty exist; "address" if the annotation is not here) of a field via java reflection.

User.java

public class User implements Serializable{
  @JsonProperty(value="adr")
  private Address m_address;

  public User(Address a) {
    m_address = a;
  }

  public Address getAddress() {
    return m_address;
  }

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

The reflection

dObjectMapper mapper = new ObjectMapper();
for (Field field : User.class.getDeclaredFields(){
  field.setAccessible(true);
  // Convert object to JSON string
  try {
    //TODO
    String jsonName = mapper.foobar(field);
  } catch (JsonMappingException e) {
    e.printStackTrace();
  }
}

I hope the question is understandable.

Thanks for your answer.





Aucun commentaire:

Enregistrer un commentaire