如何使用Jackson ObjectMapper获取字段类型?

时间:2015-04-28 15:18:30

标签: java json jackson

知道如何基于Jackson的ObjectMapper对象和特定类检索给定json路径的Java类型吗?

我们说我们有

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

和Jackson的ObjectMapper我想找到一种方法将String值反序列化为给定路径上的字段所代表的类型的对象(或者至少得到它的类型),例如

  • 给出" / accountOwner / age"和" 25"得到25(类型为整数)
  • 给出" / accountOwner / active"和"真"得到true(布尔类型)
  • 给出" / accountOwner / fullName"和" Johny Bravo"得到" Johny Bravo"串
  • 等...

1 个答案:

答案 0 :(得分:0)

我在这里有一个例子:

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();
}

我的豆子:

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 + "]";
    }
}

最后是Json对象(json.txt):

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

我希望这可以帮到你。