[英]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.