java – 使用Jackson定制JSON反序列化

我使用Flickr API.当调用flickr.test.login方法时,默认的JSON结果是:

{
    "user": {
        "id": "21207597@N07",
        "username": {
            "_content": "jamalfanaian"
        }
    },
    "stat": "ok"
}

我想将这个响应解析成一个Java对象:

public class FlickrAccount {
    private String id;
    private String username;
    // ... getter & setter ...
}

JSON属性应该如下映射:

"user" -> "id" ==> FlickrAccount.id
"user" -> "username" -> "_content" ==> FlickrAccount.username

不幸的是,我不能找到一个漂亮,优雅的方式来使用注释。到目前为止,我的方法是将JSON字符串读入Map< String,Object>并从中获得价值。

Map<String, Object> value = new ObjectMapper().readValue(response.getStream(),
        new TypeReference<HashMap<String, Object>>() {
        });
@SuppressWarnings( "unchecked" )
Map<String, Object> user = (Map<String, Object>) value.get("user");
String id = (String) user.get("id");
@SuppressWarnings( "unchecked" )
String username = (String) ((Map<String, Object>) user.get("username")).get("_content");
FlickrAccount account = new FlickrAccount();
account.setId(id);
account.setUsername(username);

但我认为,这是非常优雅的方式。有没有简单的方法,使用注释或定制的解串器?

这对我来说非常明显,但当然不行:

public class FlickrAccount {
    @JsonProperty( "user.id" ) private String id;
    @JsonProperty( "user.username._content" ) private String username;
    // ... getter and setter ...
}
最佳答案
您可以为此课程编写自定义解串器。它可能看起来像这样:

class FlickrAccountJsonDeserializer extends JsonDeserializer<FlickrAccount> {

    @Override
    public FlickrAccount deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        Root root = jp.readValueAs(Root.class);

        FlickrAccount account = new FlickrAccount();
        if (root != null && root.user != null) {
            account.setId(root.user.id);
            if (root.user.username != null) {
                account.setUsername(root.user.username.content);
            }
        }

        return account;
    }

    private static class Root {

        public User user;
        public String stat;
    }

    private static class User {

        public String id;
        public UserName username;
    }

    private static class UserName {

        @JsonProperty("_content")
        public String content;
    }
}

之后,您必须为您的课程定义序列化程序。你可以这样做:

@JsonDeserialize(using = FlickrAccountJsonDeserializer.class)
class FlickrAccount {
    ...
}

转载注明原文:java – 使用Jackson定制JSON反序列化 - 代码日志