Java 如何从json字符串创建JSONObject的JSONArray?

Java 如何从json字符串创建JSONObject的JSONArray?,java,json,Java,Json,我有一个Java字符串格式的json数组,根据。无论我尝试什么,结果JSONArray cadDims都是空的。没有报告例外情况。以下是尝试1代码: String dataStr = "[{\"DIMNAME\":\"d11\",\"DIMID\":\"11\"},{\"DIMNAME\":\"d12\",\"DIMID\":\"12\"}]"; try { JSONArray cadDims = new JSONArray(dataStr); } catch (JSONExceptio

我有一个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);
}
试试这个:

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);
    }

根据你的评论,我想我理解你做错了什么。您需要在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块作用域和一般作用域,以了解这种行为。您可以开始。

您在哪里看到它是空的?请提供一个。我尽可能地缩小它,而不是移除挡块。我可以在调试模式下看到它是空的,在cadDims=…之后有一个断点。它是最小的,但不完整或不可验证。请给我们一些我们可以复制的东西。谢谢你,弗朗西斯!现在工作。哎呀,真不敢相信我错过了。@user3217883为什么你说生成的数组是空的,没有错误?我可以看到它在NetBeans调试模式下是空的,在cadDims之后有一个断点。它实际上是在工作,但当我可以用调试器研究CADDIM时,它已经超出了try块,超出了范围。