2017-04-21 74 views
0

我正在写一个处理股票价值的Java应用程序。 我有一个JSON文件,该文件是这样的:从JSON创建映射

{ 
"Meta Data": 
{ 
    "1. Information": "Daily Prices , 
    "2. Symbol": "FB", 
    "3. Last Refreshed": "2017-04-21 10:24:00", 
    "4. Output Size": "Compact", 
    "5. Time Zone": "US/Eastern" 
}, 
"Time Series (Daily)": { 
    "2017-04-21 10:24:00": { 
     "1. open": "143.9000", 
     "2. high": "144.1700", 
     "3. low": "143.4600", 
     "4. close": "143.7800", 
     "5. volume": "2784942" 
    }, 
    "2017-04-20": { 
     "1. open": "142.9500", 
     "2. high": "144.2500", 
     "3. low": "142.6900", 
     "4. close": "143.8000", 
     "5. volume": "15917800" 
    }, 
    "2017-04-19": { 
     "1. open": "141.3500", 
     "2. high": "143.0400", 
     "3. low": "141.2700", 
     "4. close": "142.2700", 
     "5. volume": "15500400" 
    }, 
    "2017-04-18": { 
     "1. open": "141.2700", 
     "2. high": "141.9100", 
     "3. low": "140.6100", 
     "4. close": "140.9600", 
     "5. volume": "14790800" 
    } 
    } 
} 

我可以使用GSON股票价值的名单,但随后由于JSON是无序我真的不知道具体的股票价值的日期。

final Gson gson = new Gson(); 
    final List<String> stockValues = gson.fromJson(JSON2, JsonElement.class) 
      .getAsJsonObject() 
      .get("Time Series (Daily)") // get the divisions property 
      .getAsJsonObject() 
      .entrySet() // and traverse its key/value pairs 
      .stream() 
      .map(Entry::getValue) // discarding the keys 
      .map(JsonElement::getAsJsonObject) 
      .map(jo -> jo.get("1. open")) // take the id property from the every `division` object 
      .map(JsonElement::getAsJsonPrimitive) 
      .map(JsonPrimitive::getAsString) 
      .collect(Collectors.toList()); 

我真正需要的是使其中包含对日期股票价值的地图(“开放”)。我该怎么做?

回答

0

首先,有一个“失踪后”1。信息“: ”每日价格“ ,.该解决方案是

Map<String, Map<String, Double>> map = new HashMap<>(); 

    ObjectMapper mapper = new ObjectMapper(); 
    JsonNode node = mapper.readTree(new File("path_to_json_file")); 
    JsonNode data = node.get("Time Series (Daily)"); 

    Iterator<String> iterator = data.fieldNames(); 
    while (iterator.hasNext()) { 
     String date = iterator.next(); 
     JsonNode value = data.get(date); 

     Map<String, Double> priceMap = new HashMap<>(); 
     Iterator<String> itr = value.fieldNames(); 
     while(itr.hasNext()){ 
      String param = itr.next(); 
      JsonNode price = value.get(param); 

      priceMap.put(param.replaceAll(" ", "").split("\\.")[1], price.asDouble()); 
     } 
     map.put(date, priceMap); 
    } 
    System.out.println(map); 
} 

输出:{2017年4月18日= {体积= 1.47908E7,高= 141.91,低= 140.61,靠近= 140.96,开启= 141.27 },2017-04-21 10:24:00 = {volume = 2784942.0,high = 144.17,low = 143.46,close = 143.78,open = 143.9},2017-04-20 = {volume = 1.59178E7,high = 144.25 ,低= 142.69,close = 143.8,开= 142.95},2017-04-19 = {volume = 1.55004E7,high = 143.04,low = 141.27,close = 142.27,open = 141.35}}

+1

您的解决方案有效,非常感谢。 –