2016-07-31 27 views
0

我想從一個大的JSON文件獲取特定的集合,但我不想在JSON文件上創建所有的對象結構,因爲我只需要「電話」和 「看跌期權」 領域......如何從一個大的JSON文件獲得特定的集合

的jsonfile是這樣的:https://query2.finance.yahoo.com/v7/finance/options/AEIS?formatted=true&lang=en-US&region=US&corsDomain=finance.yahoo.com

,這是我的類選項...不張貼getter和setter ..

public class Option { 

    public enum Type { PUT, CALL } 
    @JsonIgnore 
    public Type type; 
    @JsonProperty("contractSymbol") 
    private String contractSymbol; 
    @JsonProperty("contractSize") 
    private String contractSize; 
    @JsonProperty("currency") 
    private String currency; 

    @JsonProperty("inTheMoney") 
    private boolean inTheMoney; 
    @JsonProperty("percentChange") 
    private Field percentChange; 
    @JsonProperty("strike") 
    private Field strike; 
    @JsonProperty("change") 
    private Field change; 
    @JsonProperty("impliedVolatility") 
    private Field impliedVolatility; 
    @JsonProperty("ask") 
    private Field ask; 
    @JsonProperty("bid") 
    private Field bid; 
    @JsonProperty("lastPrice") 
    private Field lastPrice; 

    @JsonProperty("volume") 
    private LongFormatField volume; 
    @JsonProperty("lastTradeDate") 
    private LongFormatField lastTradeDate; 
    @JsonProperty("expiration") 
    private LongFormatField expiration; 
    @JsonProperty("openInterest") 
    private LongFormatField openInterest; 
} 

,我試圖得到這樣的數據...

List<Option> res = JSON_MAPPER.readValue(new URL(link), new TypeReference<List<Option>>() {}); 

for(Option o: res){ 
    o.type = Option.Type.CALL; 
    System.out.println(o.toString()); 
} 

AAAND這是個例外......

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token 
    at [Source: https://query2.finance.yahoo.com/v7/finance/options/AEIS?formatted=true&lang=en-US&region=US&corsDomain=finance.yahoo.com; line: 1, column: 16] (through reference chain: java.util.HashMap["optionChain"]) 

回答

0

的問題是,從源頭上JSON回報始於對象屬性,「optionChain」,傑克遜試圖反序列化作爲HashMap,但反序列化後,您期望List

正如你所說,你只需要在JSON的「電話」和「看跌期權」,你可以用ObjectMapper.readTree讓整個JsonNode,再由JsonNode.findValue找到「來電」的節點,最後反序列化的節點。以下是一個例子:

String link = "https://query2.finance.yahoo" + 
      ".com/v7/finance/options/AEIS?formatted=true&lang=en-US&region=US&corsDomain=finance.yahoo.com"; 
ObjectMapper mapper = new ObjectMapper(); 
JsonNode jsonNode = mapper.readTree(new URL(link)); 
JsonNode calls = jsonNode.findValue("calls"); 
List<Option> callOptions = mapper.readValue(calls.traverse(), new TypeReference<List<Option>>() {});