【问题标题】:Why am I getting a JSON exception while calling .getJSONObject()?为什么在调用 .getJSONObject() 时出现 JSON 异常?
【发布时间】:2020-08-18 10:50:23
【问题描述】:

我想在 JSON 响应中生成带有 URI 的 JSON,但是当我尝试获取键的值时出现 JSON 异常。这里的 fragmentdataservice 用于获取 JSON 数据,它工作正常,我正在使用内容片段创建 API。

String requestURI = req.getRequestURI();
String contentFragmentName = requestURI.substring(requestURI.indexOf('.') +
    1, requestURI.lastIndexOf('.'));

resp.setContentType("application/json");
response = fragmentDataService.getContentFragment(contentFragmentName);

String contentReference = response.getJSONObject("poolingInfo").toString();
JSONObject contentData = fragmentDataService.getContentFragment(contentReference);
response.put("poolingInfo", contentData);

【问题讨论】:

  • 您遇到了什么异常?您确定响应是有效的 JSON 文档吗?

标签: java json api content-management-system aem


【解决方案1】:

如果您尝试使用getJSONObject() 方法将String 数据或JSONArray 数据作为JSONObject 读取,则会引发JSON 异常。 如果您不确定返回的对象类型是什么,请先使用:

Object temp = response.get("poolingInfo");
if(null != temp && temp instanceof JSONObject) {
    String contentReference = ((JSONObject) temp).toString();
}

【讨论】:

    猜你喜欢
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    相关资源
    最近更新 更多