为什么在调用.getJSONObject时出现JSON异常?

问题描述

我想在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);

解决方法

如果您尝试使用String方法读取JSONArray数据或作为JSONObject的{​​{1}}数据,则会抛出

JSON异常。 如果不确定要返回的对象是什么类型,请首先使用:

getJSONObject()