【问题标题】:How to convert json response to an array?如何将json响应转换为数组?
【发布时间】:2020-06-11 15:10:16
【问题描述】:

我希望列出 json 响应中的值,而不是显示为逗号分隔的单行响应。以下是我的部分代码:

URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(DaoIntegration.getCustomSearchBody().getBytes());
os.flush();
os.close();
if (con.getResponseCode() != 200) {
    throw new RuntimeException("Failed : HTTP error code : " +
        con.getResponseCode());
} else {
    content = (InputStream) con.getInputStream();
    result = org.apache.commons.io.IOUtils.toString(content, "UTF-8");
    jsonObject = new JSONObject(result);

    String MemberResponse = jsonObject.get("MemberResponse").toString();
    String[] members = MemberResponse.split(",");
    System.out.println("MemberResponse: " + members);
}

现在得到的是这种格式:

MemberResponse: { "AnniversaryDate": null, "EmirateResidence": null, "ReferralCode": "ERXEN0B1NJ", "Email": "abc@gmail.com", "TotalPointsLapsed": "0" }

我希望格式如下图所示:

【问题讨论】:

  • 您可以使用对象映射器将 jsonobject 转换为 hashmap。然后根据需要从 hashmap 转换为任何形式。

标签: java json api rest


【解决方案1】:

你能试试这个美化你的 json 和打印吗?请确保添加必要的 jackson.core 作为依赖项。

ObjectMapper mapper = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);

【讨论】:

    猜你喜欢
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 2021-08-02
    相关资源
    最近更新 更多