我有像这样的json
{
"name": "john",
"photo_urls":
{
"large": "http://www.server.com/john_photo.jpg"
}
}
我想在一个类中反序列化它,比如
public class Person
{
String name;
String photoUrl;
}
而不是
public class Person
{
String name;
public class photo_urls
{
String large;
}
}
使用数据绑定和注释@JsonProperty可以使用Jackson吗?或者是否有必要使用流API?
感谢您的帮助。
答案 0 :(得分:0)
您可以考虑使用Map<String,String>
类型的setter方法或构造函数参数,从中可以获取url字段值。这是一个例子:
public class JacksonDeserialize {
private static final String JSON = "{\n" +
" \"name\": \"john\",\n" +
" \"photo_urls\":\n" +
" {\n" +
" \"large\": \"http://www.server.com/john_photo.jpg\"\n" +
" }\n" +
"}";
public static class Person
{
private String name;
private String photoUrl;
@JsonCreator
public Person(@JsonProperty("name") String name, @JsonProperty("photo_urls") Map<String, String> photoUrl) {
this.name = name;
this.photoUrl = photoUrl.get("large");
}
@Override
public String toString() {
return "Person{" +
"photoUrl='" + photoUrl + '\'' +
", name='" + name + '\'' +
'}';
}
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(JSON, Person.class));
}
}
输出:
Person{photoUrl='http://www.server.com/john_photo.jpg', name='john'}