[英]How to parse/decode JSON using Java from bufferReader output?
I got a JSON output. 我得到了JSON输出。 Now need to parse the JSON String.
现在需要解析JSON String。
Some part of my code: 我的代码的一部分:
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + query_en);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
How to parse the output using Java? 如何使用Java解析输出?
There are a lot of third party libs for parsing JSON in java. 在Java中,有很多用于解析JSON的第三方库。 For example jackson:
例如杰克逊:
private void test(BufferedReader reader) {
ObjectMapper mapper = new ObjectMapper();
try {
Map<String, Object> map = mapper.readValue(reader, new TypeReference<Map<String, String>>() {
});
System.out.println(map);
} catch (IOException e) {
e.printStackTrace();
}
}
Gson: GSON:
private void test2(BufferedReader r) {
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(r, type);
System.out.println(myMap);
}
您可以使用https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.0 。
JsonObject jsonData = new JsonParser().parse(response.toString()).getAsJsonObject();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.