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