Getting properties form JSON response [duplicate]

问题: This question already has an answer here: How to parse JSON in Java 29 answers I've got an response from API which I want to get data from. How am...

问题:

This question already has an answer here:

I've got an response from API which I want to get data from. How am I able to map this response to object by RestTemplate but without getting all the fields? I dont want to create nested objects. I'd expect to get result like this:

@JsonProperty("id")
private long id;
@JsonProperty("user.userName") <-- how to achive this?
private String userName;
@JsonProperty("imagies.thumbnail.url") <-- how can i get only this 1 property?
private URL standardResolutionUrlOfPhoto;

Response:

 "data": [
        {
            "id": "xxxxx",
            "user": {
                "username": "xxxxx"    <--- I dont want  to create User user field!
            },
            "images": {
                "thumbnail": {
                    "width": 150,
                    "height": 150,
                    "url": "xxxxxx"
                },
                "low_resolution": {
                    "width": 320,
                    "height": 320,
                    "url": "xxxxx"
                },
                "standard_resolution": {
                    "width": 640,
                    "height": 640,
                    "url": "xxxx"
                }
            },

回答1:

There is a quite cool, but dirty way you can achieve this. Take a look here:

@JsonProperty("id")
private long id;
@JsonIgnore
private String userName;
@JsonIgnore
private String standardResolutionUrlOfPhoto;

@JsonProperty("user")
private void unpackUser(JsonNode user) {
    this.userName = user.get("username").asText();
}

@JsonProperty("images")
private void unpackImages(JsonNode images) {
    this.standardResolutionUrlOfPhoto = images.get("thumbnail").get("url").asText();
}

回答2:

You can use JsonPath library for reading values using a JSON path.

Similar question is already answered in other question Jsonpath with Jackson or Gson

  • 发表于 2018-07-11 16:54
  • 阅读 ( 275 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除