java JSONArray 使用範例

Posted in :

跟型別自動轉換的 javascript 與 python 相比, JSONArray 在 java 裡使用起來有點 卡卡的, 不是很直覺.

瀏覽 JsonArray, 並於每一個 array 裡, 再取出 json 範例,

Foreach with JSONArray and JSONObject
https://stackoverflow.com/questions/33215539/foreach-with-jsonarray-and-jsonobject

Seems like you can’t iterate through JSONArray with a for each. You can loop through your JSONArray like this:

for (int i=0; i < arr.length(); i++) {
    arr.getJSONObject(i);
}

存取 json object 範例:

import org.json.JSONObject;
public class Test {
    public static void main(String args[]){
       JSONObject jo = new JSONObject("{ \"abc\" : \"def\" }");
       System.out.println(jo.toString());
    }
}

json array 放進 json object 範例:

     JSONArray family = new JSONArray();
     JSONObject father = new JSONObject();
     father.put("name", "Max");
     father.put("age", 40);
     JSONObject mother = new JSONObject();
     mother.put("name","Honey");
     mother.put("age",41);
     family.add(father);
     family.add(mother);
     student.put("family", family);

json object 取出 json array

student.getJSONArray("family")

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *