[英]Java exception handling: JSONObject cannot convert JSONArray
private String getExpenseDtl() throws Exception {
CommonDO commonDO = new CommonDO(this.ou);
HttpServletRequest request = ServletActionContext.getRequest();
try {
String getData = '<Root></Root>' //Sql returned xml result
if (!getData.equals("~") && !getData.equals("") && !getData.equals("<Root/>")) {
JSONObject xmlJSONObj = XML.toJSONObject(getData);
JSONArray headerFormat = null;
if (xmlJSONObj.has("Root")) {
if (xmlJSONObj.getJSONObject("Root").has("AmountDtl")) //Here i am getting error
{
Object jsonObjData = xmlJSONObj.getJSONObject("Root").get("AmountDtl");
if (!jsonObjData.toString().contains("[")) {
String jsonStrData = "[" + jsonObjData.toString() + "]";
headerFormat = new JSONArray(jsonStrData);
} else {
headerFormat = (JSONArray) xmlJSONObj.getJSONObject("Root").get("AmountDtl");
}
}
}
request.setAttribute("amountDetailsData", headerFormat);
} else {
getData = "~";
request.setAttribute("amountDetailsData", getData);
}
} catch (Exception e) {
getData = "~";
request.setAttribute("amountDetailsData", getData);
System.out.println("[" + new Date().toString() + "]" + e.getMessage());
String errMsg = e.toString().replaceAll("[^\\w\\s]", "");
commonDO.insertLogDetails(errMsg);
}
return "expense";
}
在 executeQuery 之后,我得到了一些 XML 格式的结果。 在检查xmlJSONObj.getJSONObject("Root").has("AmountDtl")
时,我得到一个异常"JSONObject["Root"] is not a JSONObject" 。 如何处理这个异常?
在你的情况下。
你有
String getData = '<Root></Root>';
如果将其转换为 JSONObject,您会得到类似的结果。
{
"Root": {},
}
根据您所说的,您在这里遇到了异常:
if (xmlJSONObj.getJSONObject("Root").has("AmountDtl"))
getJSONObject 正在尝试获取嵌套在 JSONObject 中的 JSONObject 一个有用的示例,例如,如果您有一个如下所示的 JSONObject:
{"isbn": "123-456-222",
"author":
{
"lastname": "Doe",
"firstname": "Jane"
},
"editor":
{
"lastname": "Smith",
"firstname": "Jane"
},
"title": "The Ultimate Database Study Guide",
"category": ["Non-Fiction", "Technology"]
}
在此示例中,您可以有一个 getJSONObject("author") 并获取 JSONObject:
{ "lastname": "Doe",
"firstname": "Jane"
}
这里有一些关于它的信息: https ://www.ibm.com/docs/no/db2/11.5?topic=documents-json-nested-objects
你能发布一个你的变量getData的例子吗? 在您发布的示例中尚不清楚,但我会说您的问题是创建 JSONObject 的方式不会创建嵌套的 JSONObject
我找到了答案,我正在从 SQl 服务器获取结果
String getData = '<Root></Root>';
这里 JSON 对象不能有值,它只有一个根标签,所以空的 json 对象不能转换 json 数组,所以我有一个异常,在我将结果更改为
String getData = '<Root><dta/></Root>';
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.