jackson 如何正确地从一个大的json响应中获取特定的行?

djmepvbi  于 2022-11-23  发布在  其他
关注(0)|答案(1)|浏览(131)

我有一个很大的json响应:

{
  "data" : {
    "type" : "gif",
    "id" : "BM10Y3Qq3EwK3z8yQd",
    "url" : "https://giphy.com/gifs/ramseysolutions-money-gone-BM10Y3Qq3EwK3z8yQd",
    "slug" : "ramseysolutions-money-gone-BM10Y3Qq3EwK3z8yQd",
    "bitly_gif_url" : "https://gph.is/2mc28WP",
    "bitly_url" : "https://gph.is/2mc28WP",
    "embed_url" : "https://giphy.com/embed/BM10Y3Qq3EwK3z8yQd",
    "username" : "ramseysolutions",
    "source" : "",
    "title" : "rachel cruze money GIF by Ramsey Solutions",
    "rating" : "g",
    "content_url" : "",
    "source_tld" : "",
    "source_post_url" : "",
    "is_sticker" : 0,
    "import_datetime" : "2018-07-12 12:40:11",
    "trending_datetime" : "0000-00-00 00:00:00",
    "images" : {
      "fixed_width_still" : {
        "height" : "113",
        "size" : "14977",
        "url" : "https://media4.giphy.com/media/BM10Y3Qq3EwK3z8yQd/200w_s.gif?cid=294ee95f49badf517d33e5cd874941ff542e5d2559cf692c&rid=200w_s.gif&ct=g",
        "width" : "200"
      },
      "preview_gif" : {
        "height" : "99",
        "size" : "48529",
        "url" : "https://media4.giphy.com/media/BM10Y3Qq3EwK3z8yQd/giphy-preview.gif?cid=294ee95f49badf517d33e5cd874941ff542e5d2559cf692c&rid=giphy-preview.gif&ct=g",
        "width" : "176"
      },
      
     ...

我只想从那里得到data -> urldata -> embed_url。这怎么能正确地完成呢?我尝试添加@JsonProperty to setter

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class GifUrlDto {
    private String url;
    private String embedUrl;

    @JsonProperty("data")
    public void setUrl(Map<String, String> data) {
        this.url =data.get("url");
        this.embedUrl = data.get("embed_url");
    }
}

当我试图从函数返回它时:

@GetMapping("/random")
    GifUrlDto getRandomGByExchangeRates();

然后我得到一个错误:

Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 665] (through reference chain: com.alfa.bank.project.gifAndExchangeRate.dto.GifUrlDto["data"]->java.util.LinkedHashMap["images"])] with root cause

我需要做一个去卵巢的人吗,或者我能做得更好吗?

dy2hfwbg

dy2hfwbg1#

我只想从那里得到data -〉url和data -〉embed_url。我需要做一个desarilizer吗,或者我能做得更好吗?
你可以不使用反序列化器,也可以使用反序列化器。如果没有反序列化器,你可以分离出json文件中你感兴趣的部分,然后使用JsonNode#at方法将其转换为JsonNode对象(如果你必须在代码中提取一次属性,这很好):

JsonNode data = mapper.readTree(json).at("/data");
String url = data.get("url").asText(); //<--url is a string
String embedUrl = data.get("embed_url").asText();//<-- embed_url is a string
GifUrlDto dto = new GifUrlDto(url, embedUrl);

您也可以为GifUrlDto类编写一个特定的反序列化器,重复使用上面的代码(如果您必须反序列化多个对象,这很好):

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@JsonDeserialize(using = GifUrlDtoDeserializer.class)//<--added annotation
public class GifUrlDto {
    private String url;
    private String embedUrl;
}

public class GifUrlDtoDeserializer extends StdDeserializer<GifUrlDto>{

    public GifUrlDtoDeserializer() {
        super(GifUrlDto.class);
    }

    @Override
    public GifUrlDto deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
        final ObjectCodec codec = jp.getCodec();
        JsonNode root = codec.readTree(jp);
        JsonNode data = root.at("/data");
        String url = data.get("url").asText();
        String embedUrl = data.get("embed_url").asText();
        return new GifUrlDto(url, embedUrl); 
    }
}

//using the deserializer
GifUrlDto dto = mapper.readValue(json, GifUrlDto.class);

相关问题