标签:void int 允许 pac 疑问 class sign 添加 log
net.sf.json 需要的 jar:

注意版本,部分版本之间会冲突。
package com.ikoo;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class TestJSON {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
/**
* public Object put(Object key, Object value)
* 将value映射到key下
* 如果此JSONObject对象之前存在一个value在这个key下,那么当前的value会替换掉之前的value
*/
jsonObject.put("one", "first");
// jsonObject: {"one":"first"}
System.out.println("jsonObject: " + jsonObject.toString());
jsonObject.put("two", "second");
// jsonObject: {"one":"first","two":"second"}
System.out.println("jsonObject: " + jsonObject.toString());
jsonObject.put("two", "cover");
// jsonObject: {"one":"first","two":"cover"}
System.out.println("jsonObject: " + jsonObject.toString());
jsonObject.put("one", null);// value为null的话,直接移除key
// jsonObject: {"two":"cover"}
System.out.println("jsonObject: " + jsonObject.toString());
/**
* public JSONObject accumulate(String key, Object value)
* 累积value到这个key下
* 1.如果当前已经存在一个value在这个key下,那么会有一个JSONArray将存储在这个key下来保存所有累积的value
* 2.如果已经存在一个JSONArray,那么当前的value就会添加到这个JSONArray中
*
*/
JSONObject jsonObj = new JSONObject();
jsonObj.accumulate("Servers", null);// 允许value为null
jsonObj.accumulate("Servers", "Tomcat");
jsonObj.put("Codes", "Java");
jsonObj.accumulate("Codes", "JavaScript");
// jsonObj: {"Servers":[null,"Tomcat"],"Codes":["Java","JavaScript"]}
System.out.println("jsonObj: " + jsonObj.toString());
/**
* public JSONObject element(String key, Object value)
*/
JSONObject object = new JSONObject();
object.element("price", "500");
object.element("price", "1000");
// object: {"price":"1000"} 疑问: 这和put有何区别??? 说好的会调用accumulate呢???
System.out.println("object: " + object.toString());
}
}
控制台打印:
jsonObject: {"one":"first"}
jsonObject: {"one":"first","two":"second"}
jsonObject: {"one":"first","two":"cover"}
jsonObject: {"two":"cover"}
jsonObj: {"Servers":[null,"Tomcat"],"Codes":["Java","JavaScript"]}
object: {"price":"1000"}
P.S. 网上的帖子对 element 方法介绍都是如下:
Put a key/value pair in the JSONObject. If the value is null, then the key will be removed from the JSONObject if it is
present. If there is a previous value assigned to the key, it will call accumulate.
翻译:
public JSONObject element (String key, Object value) 将键/值对放到这个JSONObject对象里面。如果当前value为空(null),那么如果这个key存在的话,这个key就会移除掉。如果这
个key之前有value值,那么此方法会调用accumulate()方法。
但是,亲测,却不尽然,结果并不是如上的预期的效果。所以就纳闷了,网上关于这样的帖子好多,都是一样的,想必是直接 CV 大法,不过我就是很纳闷,为何 element 不是文档说的那样?!
net.sf.json - put、accumulate、element
标签:void int 允许 pac 疑问 class sign 添加 log
原文地址:http://www.cnblogs.com/ikoo4396/p/7779176.html