鉴于以下json:
{
"User":{
"firstname":"john",
"gender":"female",
"verified":"no"
}
}
有没有办法删除/忽略“用户”节点,所以我可以使用jackson绑定?你看,如果我尝试这样做的话:
User user= mapper.readValue(content, User.class); //where content is the json above
用户类是:
public class User
{
String _firstname, _gender, _verified;
[getters and setters]
}
它出错了:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: 无法识别的字段“用户”
我知道我可以初始化User类并且只是手动设置setter但是我想知道是否可以或更好地删除/忽略“User”节点?
答案 0 :(得分:3)
在JSON的根目录中,您有另一个名为User
的JSON对象。您不能忽略它,因为它包含您要提取的对象。您需要做的是从嵌套的JSON对象而不是根JSON对象中提取对象。
您可以通过获取嵌套的JSON对象来实现。
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(content);
User user = mapper.readValue(node.get("User").traverse(), User.class);
此外,我不确定杰克逊是否支持像{/ 1>}那样悬挂,
"verified":"no",
答案 1 :(得分:2)
此解决方案通过在rootName
上设置ObjectReader
来使用纯杰克逊:
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
public class User {
public static void main(String[] args) throws JsonProcessingException, IOException {
String json = "{\"User\":{\"firstname\":\"john\",\"gender\":\"female\",\"verified\":\"no\"}}";
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.reader(User.class).withRootName("User");
User user = reader.readValue(json);
System.out.println(user.getFirstname());
}
private String firstname;
private String lastname;
private String verified;
private String gender;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getVerified() {
return verified;
}
public void setVerified(String verified) {
this.verified = verified;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}