如何使用来自bufferReader输出的Java解析/解码JSON?

时间:2017-03-20 05:13:30

标签: java json parsing decode

我有一个JSON输出。现在需要解析JSON字符串。

我的代码的一部分:

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());

如何使用Java解析输出?

2 个答案:

答案 0 :(得分:0)

在java中解析JSON有很多第三方库。例如杰克逊:

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:

    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);
}

答案 1 :(得分:0)

您可以使用https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.0

JsonObject jsonData = new JsonParser().parse(response.toString()).getAsJsonObject();