[英]how to create JSONArray of JSONObject from json string?
根据jsonlint ,我在Java字符串中有一个格式正确的json数组。 无论我如何尝试,生成的JSONArray cadDims都是空的。 没有例外的报告。 这是尝试1的代码:
String dataStr = "[{\"DIMNAME\":\"d11\",\"DIMID\":\"11\"},{\"DIMNAME\":\"d12\",\"DIMID\":\"12\"}]";
try {
JSONArray cadDims = new JSONArray(dataStr);
} catch (JSONException ex) {
Logger.getLogger(EnCad.class.getName()).log(Level.SEVERE, null, ex);
}
这是尝试2:
String dataStr = "{\"dataStr\":[{\"DIMNAME\":\"d11\",\"DIMID\":\"11\"},{\"DIMNAME\":\"d12\",\"DIMID\":\"12\"}]}";
try {
JSONObject obj = new JSONObject(dataStr);
JSONArray cadDims = obj.getJSONArray("dataStr");
} catch (JSONException ex) {
Logger.getLogger(EnCad.class.getName()).log(Level.SEVERE, null, ex);
}
这是尝试3:
dataStr = "[{\"DIMNAME\": \"d11\",\"DIMID\": 11}, {\"DIMNAME\": \"d12\",\"DIMID\": 12}]";
try {
JSONArray cadDims = (JSONArray)new JSONTokener(dataStr).nextValue();
} catch (JSONException ex) {
Logger.getLogger(EnCad.class.getName()).log(Level.SEVERE, null, ex);
}
我想我会根据您的评论了解您在做什么错。 您需要在try catch块外部声明cadDims
,然后在try catch块内部初始化值,如下所示:
dataStr = "[{\"DIMNAME\": \"d11\",\"DIMID\": 11}, {\"DIMNAME\": \"d12\",\"DIMID\": 12}]";
JSONArray cadDims;
try {
cadDims = new JSONArray(dataStr);
} catch (JSONException ex) {
Logger.getLogger(EnCad.class.getName()).log(Level.SEVERE, null, ex);
}
if(cadDims != null){
//Do something with cadDims
}
如果在try catch块内声明并初始化了变量,则在该try catch块外将无法再访问该变量。 我建议阅读一般的try catch块作用域和作用域以了解此行为。 您可以从这里开始。
尝试这个:
JSONArray cadDims = null;
String dataStr = "[{\"DIMNAME\":\"d11\",\"DIMID\":\"11\"},{\"DIMNAME\":\"d12\",\"DIMID\":\"12\"}]";
try {
cadDims = new JSONArray(dataStr);
} catch (JSONException ex) {
Logger.getLogger(EnCad.class.getName()).log(Level.SEVERE, null, ex);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.