2016-10-18 60 views
0

我试图提取key中的第一个元素和下面的json数据中的值。然而,我见过的大多数例子都使用org.json,它似乎已经过时了?用下面的json文件做这件事最好的方法是什么?在不使用org.json的情况下解析java中的json文件

"data": [ 
    { 
     "key": [ 
     "01", 
     "2015" 
     ], 
     "values": [ 
     "2231439" 
     ] 
    }, 
    { 
     "key": [ 
     "03", 
     "2015" 
     ], 
     "values": [ 
     "354164" 
     ] 
    }, 
    { 
     "key": [ 
     "04", 
     "2015" 
     ], 
     "values": [ 
     "283712" 
     ] 
    } 
    ] 
} 

这是我如何得到json响应并将其存储在一个字符串中,该字符串从上面提供了json数据。

HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); 
      httpConnection.setRequestMethod("POST"); 
      httpConnection.setDoOutput(true); 
      OutputStream os = httpConnection.getOutputStream(); 
      os.write(jsonText.getBytes()); 
      os.flush(); 
      os.close(); 

      int responseCode = httpConnection.getResponseCode(); 
      System.out.println(responseCode); 

      if (responseCode == HttpURLConnection.HTTP_OK) { 
       BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); 
       String input; 
       StringBuffer response = new StringBuffer(); 

       while ((input = br.readLine()) != null) { 
        response.append(input); 
       } 
       br.close(); 
       String responseJson = response.toString(); 
+0

笏你的意思是过时的? – Nyakiba

+0

@Nyakiba 它的正确性,org.json可能不是最好的。还有其他几个JSON Apis,像Gson,Jackson,Genson和FlexJson一样被推荐使用。 结帐在此链接的评论部分的讨论http://stackoverflow.com/a/18998203/3838328 – Kamal

+0

似乎我一直在黑暗中 – Nyakiba

回答

0

那么我尝试了下面的使用杰克逊API。基本上,我创建了一个类,它是整个JSON数据

public class MyData { 

    private List<Map<String, List<String>>> data; 

    public List<Map<String, List<String>>> getData() { 
     return data; 
    } 

    public void setData(List<Map<String, List<String>>> data) { 
     this.data = data; 
    } 

} 

写了下面的解析器利用杰克逊API的Java表示,但是在你所描述的JSON提到“钥匙” ,将具有值列表作为字符串。

对于e.g都和2015年将在列表为“钥匙”项目。

请注意,我已将您的JSON数据转储到文件中,并从中读取JSON。

public static void main(String[] args) { 

    ObjectMapper mapper = new ObjectMapper(); 
    try { 

     MyData myData = mapper.readValue(new File("data"), MyData.class); 

     for (Map<String, List<String>> map : myData.getData()) { 

      // To retrieve the first element from the list // 
      // map.get("key") would return a list 
      // in order to retrieve the first element 
      // wrote the below 

      System.out.println(map.get("key").get(0)); 
     } 

    } catch (JsonGenerationException e) { 
     e.printStackTrace(); 
    } catch (JsonMappingException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

注:如您在字符串中检索的JSON,请使用下面的代码

MyData myData = mapper.readValue(responseJson, MyData.class); 
相关问题