![](/img/trans.png)
[英]Parsing internal JSON file in JSONArray in Java using org.json
[英]Parsing json file in java without using org.json
我正在尝试从以下json数据中提取key中的第一个元素和值。 但是,我见过的大多数示例都在使用似乎已经过时的org.json? 使用以下json文件执行此操作的最佳方法是什么?
"data": [
{
"key": [
"01",
"2015"
],
"values": [
"2231439"
]
},
{
"key": [
"03",
"2015"
],
"values": [
"354164"
]
},
{
"key": [
"04",
"2015"
],
"values": [
"283712"
]
}
]
}
这就是我获取json响应并将其存储在String中的方式,该String从上面给出了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();
如果您想要替代方案,可以尝试使用Google的gson吗? https://github.com/google/gson
好吧,我尝试了以下使用Jackson API的方法。 基本上,我创建了一个类,它将是整个JSON数据的Java表示形式
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;
}
}
使用Jackson的API编写了下面的解析器,但是您所描述的JSON中提到的“键”的值列表为String。
例如, 01和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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.