簡體   English   中英

JAX-RS / Jackson - 使用未知的根元素名稱反序列化JSON?

[英]JAX-RS/Jackson — Deserialize JSON with Unknown Root Element Name?

我正在編寫一個RESTeasy代理客戶端來使用Apple的API來檢索他們的iTunes類別列表。 查詢有關給定類別的信息時,例如使用以下URL:

https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/genres?id=1420

...你得到一個如下所示的JSON響應:

{  
   "1420":{  
      "name":"Self-Help",
      "id":"1420",
      "url":"https://itunes.apple.com/us/genre/podcasts-health-self-help/id1420?mt=2",
      "rssUrls":{  
         "topVideoPodcastEpisodes":"https://itunes.apple.com/us/rss/topvideopodcastepisodes/genre=1420/json",
         "topAudioPodcasts":"https://itunes.apple.com/us/rss/topaudiopodcasts/genre=1420/json",
         "topVideoPodcasts":"https://itunes.apple.com/us/rss/topvideopodcasts/genre=1420/json",
         "topPodcasts":"https://itunes.apple.com/us/rss/toppodcasts/genre=1420/json",
         "topAudioPodcastEpisodes":"https://itunes.apple.com/us/rss/topaudiopodcastepisodes/genre=1420/json",
         "topPodcastEpisodes":"https://itunes.apple.com/us/rss/toppodcastepisodes/genre=1420/json"
      },
      "chartUrls":{  
         "videoPodcastEpisodes":"https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/charts?cc=us&g=1420&name=VideoPodcastEpisodes",
         "podcasts":"https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/charts?cc=us&g=1420&name=Podcasts",
         "audioPodcastEpisodes":"https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/charts?cc=us&g=1420&name=AudioPodcastEpisodes",
         "audioPodcasts":"https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/charts?cc=us&g=1420&name=AudioPodcasts",
         "podcastEpisodes":"https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/charts?cc=us&g=1420&name=PodcastEpisodes",
         "videoPodcasts":"https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/charts?cc=us&g=1420&name=VideoPodcasts"
      }
   }
}

我正在嘗試使用JAXB和Jackson將此JSON響應映射到Java對象。 但是,“1420”根元素名稱似乎導致了問題,因為我在調用客戶端時遇到以下異常:

Unrecognized field "1420" (class foo.bar.ITunesCategoryList), not marked as ignorable

我的JAXB類看起來像這樣:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ITunesCategory implements TransferObject {

    private static final long serialVersionUID = 3443545925023804457L;

    @XmlElement(name = "id")
    @JsonProperty("id")
    private String identifier = null;

    @XmlElement
    private String name = null;

    @XmlElementWrapper(name = "subgenres")
    private List<ITunesCategory> subcategories = new ArrayList<ITunesCategory>();

    ...
}

我甚至嘗試創建一個包裝類,因為搜索可能會導致返回多個類別。 它看起來像這樣:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ITunesCategoryList implements TransferObject {

    private static final long serialVersionUID = 3303125979016445238L;

    @XmlElement
    private List<ITunesCategory> categories = new ArrayList<ITunesCategory>();

    ...
}

但是,無論我指定哪個類作為我的返回類型,我都會得到相同的錯誤,因為類別標識符是JSON對象的根元素名稱。

有沒有辦法告訴JAXB / Jackson / JAX-RS / RESTeasy忽略根元素名稱,只是將底層對象映射到Java? 我無法在開發/編譯時知道根元素名稱,因為它直接對應於搜索返回的結果。 有什么辦法可以解決這個異常嗎? 謝謝你提供的所有幫助!

我無法找到動態忽略根目錄,至少沒有任何適合JAX-RS環境的東西。 我唯一能想到的就是編寫一個自定義反序列化器,然后跳過根節點。 就像是

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;

public abstract class IHateRootElemsJsonDeserializer<T> extends JsonDeserializer<T> {

    private final ObjectMapper mapper = new ObjectMapper();
    private final Class<T> cls;

    public IHateRootElemsJsonDeserializer(Class<T> cls) {
        this.cls = cls;
    }

    @Override
    public T deserialize(JsonParser jp, DeserializationContext dc) 
            throws IOException, JsonProcessingException {
       JsonNode rootNode = jp.getCodec().readTree(jp);
       Map.Entry<String,JsonNode> field = rootNode.fields().next();
       JsonNode node = field.getValue();
       T result = mapper.convertValue(node, cls);
       return result;
    }  
}

然后用具體類型擴展它。

public class GenreDeserializer extends IHateRootElemsJsonDeserializer<Genre>{

    public GenreDeserializer() {
        super(Genre.class);
    }
}

這是使用您在上面提供的確切JSON的測試

public class Test {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        GenreDeserializer deserializer = new GenreDeserializer();
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Genre.class, deserializer);
        mapper.registerModule(module);

        Genre genre = mapper.readValue(JSON_FILE, Genre.class);
        System.out.println(genre);

        genre = mapper.readValue(JSON_FILE, Genre.class);
        System.out.println(genre);
    }

    static final File JSON_FILE = new File("json.json");
}

該模型

public class Genre {

    public String id;
    public String name;
    public String url;
    public RssUrls rssUrls;
    public ChartUrls chartUrls;

    @Override
    public String toString() {
        return "Category{" + "id=" + id + ", name=" 
                + name + ", url=" + url + ", rssUrls=" + rssUrls + '}';
    }

    public static class RssUrls {
        public String topVideoPodcastEpisodes;
        public String topAudioPodcasts;
        public String topVideoPodcasts;
        public String topPodcasts;
        public String topAudioPodcastEpisodes;
        public String topPodcastEpisodes;

        @Override
        public String toString() {
            return "RssUrls{" + "topVideoPodcastEpisodes=" + topVideoPodcastEpisodes 
                    + ", topAudioPodcasts=" + topAudioPodcasts 
                    + ", topVideoPodcasts=" + topVideoPodcasts 
                    + ", topPodcasts=" + topPodcasts 
                    + ", topAudioPodcastEpisodes=" + topAudioPodcastEpisodes 
                    + ", topPodcastEpisodes=" + topPodcastEpisodes + '}';
        }

    }

    public static class ChartUrls {
        public String videoPodcastEpisodes;
        public String podcasts;
        public String audioPodcastEpisodes;
        public String audioPodcasts;
        public String podcastEpisodes;
        public String videoPodcasts;

        @Override
        public String toString() {
            return "ChatUrls{" + "videoPodcastEpisodes=" + videoPodcastEpisodes 
                    + ", podcasts=" + podcasts 
                    + ", audioPodcastEpisodes=" + audioPodcastEpisodes 
                    + ", audioPodcasts=" + audioPodcasts 
                    + ", podcastEpisodes=" + podcastEpisodes
                    + ", videoPodcasts=" + videoPodcasts + '}';
        }   
    }
}

要在JAX-RS中配置ObjectMapper ,您可以查看這篇文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM