简体   繁体   中英

How to get field type using Jackson ObjectMapper?

Any idea how to retrieve Java type for given json path based on Jackson's ObjectMapper object and particular Class?

Let's say we have

class User {
    String fullName;
    Integer age;
    Boolean active;
    // ...
}
class Account {
    @JsonProperty("accountOwner")
    User owner;
    // ...
}

and Jackson's ObjectMapper I'd like to find a way to deserialize String value to object of type represented by the field on given path (or at least get its type), eg

  • given "/accountOwner/age" and "25" get 25 (of type Integer)
  • given "/accountOwner/active" and "true" get true (of type Boolean)
  • given "/accountOwner/fullName" and "Johny Bravo" get "Johny Bravo" String
  • etc ...

I have an example here:

User user = new User();
ObjectMapper mapper = new ObjectMapper();
try {
     user = mapper.readValue(new File("D:\\json.txt"), User.class);
    System.out.println("user : " + user);
} catch (Exception e) {
    e.printStackTrace();
}

My bean:

public class User {
    String fullName;
    Integer age;
    Boolean active;
    /**
     * @return the fullName
     */
    public String getFullName() {
        return fullName;
    }
    /**
     * @param fullName the fullName to set
     */
    public void setFullName(String fullName) {
        this.fullName = fullName;
    }
    /**
     * @return the age
     */
    public Integer getAge() {
        return age;
    }
    /**
     * @param age the age to set
     */
    public void setAge(Integer age) {
        this.age = age;
    }
    /**
     * @return the active
     */
    public Boolean getActive() {
        return active;
    }
    /**
     * @param active the active to set
     */
    public void setActive(Boolean active) {
        this.active = active;
    }

    @Override
    public String toString() {
        return "User [fullName=" + fullName + ", age=" + age + ", " +
                "active=" + active + "]";
    }
}

And finally the Json object (json.txt):

{"fullName":"Pedro Gamarra","age":30,"active":true}

I hope this can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM