JSON-put,element,accumulate的用法,區別

  • 示例代碼
package com.qlfg.mvc.spring.controller.home;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Created by QINGLAN on 2017/7/20.
 */
public class Test1 {
    public static void main(String[] args)
    {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("city","北京市");
        jsonObject.put("street","博物館");

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("user","zjl");
        jsonObject1.put("age","12");
        jsonObject1.put("address",jsonObject);
        jsonObject1.put("tel","04321234");
        jsonObject1.accumulate("tel","12356785");//累積這個value到該key下,如果key存在,則該key的值為數組
        jsonObject1.put("age","14");//如果這個key已存在,則覆蓋掉原來的value。
        jsonObject1.put("lover","secret");
        jsonObject1.element("lover","secret2");//將鍵值對放到這個JSONObject對象里面。如果當前value為空(null),那么如果這個key存在的話,這個key會被移除掉。如果這個key已存在,則覆蓋原來的value。

        JSONArray jsonArray = new JSONArray();
        jsonArray.add(0,"person1");
        jsonArray.add(1,"person2");
        jsonObject1.put("friends",jsonArray);

        System.out.println("jsonObject1="+jsonObject1);
        System.out.println("jsonObject1.getString(\"user\")="+jsonObject1.getString("user"));
        System.out.println("jsonObject1.getJSONArray(\"friend\".get(0))="+jsonObject1.getJSONArray("friends").get(0));
        System.out.println("jsonObject1.getJSONObject(\"address\").get(\"city\")="+jsonObject1.getJSONObject("address").get("city"));

    }
}
  • 輸出結果:

jsonObject1={"user":"zjl","age":"14","address":{"city":"北京市","street":"博物館"},"tel":["04321234","12356785"],"lover":"secret2","friends":["person1","person2"]}
jsonObject1.getString("user")=zjl
jsonObject1.getJSONArray("friend".get(0))=person1
jsonObject1.getJSONObject("address").get("city")=北京市

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容