- 示例代碼
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")=北京市