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

时间:2018-04-11 20:16:09

标签: java json

根据xml file snapshot,我在Java字符串中有一个格式正确的json数组。无论我尝试什么,生成的JSONArray cadDims都是空的。没有例外报道。这是尝试1代码:

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

这是尝试2:

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

这是尝试3:

#######

2 个答案:

答案 0 :(得分:0)

我想我根据你的评论理解你做错了什么。您需要在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 try块之外访问它。我建议阅读try catch块范围和范围,以了解这种行为。您可以启动here

答案 1 :(得分:-1)

试试这个:

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