0

I have a properly formatted json array in a Java string, according to jsonlint. No matter what I try, the resulting JSONArray cadDims is empty. No exceptions reported. Here is attempt 1 code:

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

Here is attempt 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);
}

Here is attempt 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);
}
user3217883
  • 1,216
  • 4
  • 38
  • 65

2 Answers2

0

I think I understand what you're doing wrong based on your comments. You need to declare cadDims outside of the try catch block, and then initialize the value inside of the try catch block, like this:

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
}

If a variable is declared and initialized inside of a try catch block, it will no longer be accessible outside of that try catch block. I suggest reading up on try catch block scopes and scopes in general to understand this behavior. You can start here.

Francis Bartkowiak
  • 1,374
  • 2
  • 11
  • 28
  • Thank you Francis! Works now. Geez, can't believe I missed that. – user3217883 Apr 11 '18 at 20:44
  • @user3217883 Why did you say the resulting array was empty and there were no errors? – shmosel Apr 13 '18 at 01:07
  • I could see it was empty in NetBeans debugging mode with a breakpoint after cadDims. It was in fact working but by the time I could study cadDims with the debugger, it was outside of the try block, out of scope. – user3217883 Apr 14 '18 at 14:51
-1

try this:

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);
    }
Yossi
  • 327
  • 2
  • 5