简体   繁体   English

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

[英]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? 任何想法如何基于杰克逊的ObjectMapper对象和特定的类为给定的json路径检索Java类型?

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 和Jackson的ObjectMapper,我想找到一种方法,可以将String值反序列化为给定路径上的字段表示的类型的对象(或至少获取其类型),例如

  • given "/accountOwner/age" and "25" get 25 (of type Integer) 给定“ / accountOwner / age”和“ 25”可获得25(类型为Integer)
  • given "/accountOwner/active" and "true" get true (of type Boolean) 给定的“ / accountOwner / active”和“ true”得到true(布尔类型)
  • given "/accountOwner/fullName" and "Johny Bravo" get "Johny Bravo" String 给定“ / accountOwner / fullName”和“ Johny Bravo”得到“ Johny Bravo”字符串
  • 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): 最后是Json对象(json.txt):

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

I hope this can help you. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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