定义
JSONObject是alibaba fastjson类库中的一种重要数据结构,,是根据 JSON 形式在 Java 中存在的对象映射。
public class JSONObject extends JSON implements Map<String, Object>, Cloneable, Serializable, InvocationHandler
- JSONObject继承自JSON类:也即JSONObject可通过toJSONString(Object)将对象序列化为JSON格式,也可通过parseObject(String, Class),将JSON反序列化为指定的对象。
- JSONObject实现了Map<String, Object>,也即是一个Map类型的数据结构,Map接口提供了很多操作map的方法。
- JSONObject还实现了Cloneable, Serializable, InvocationHandler,即支持拷贝,支持序列化与反序列化,InvocationHandler是通过一个代理实例零调用处理程序实现的接口,即标记使用Java动态代理机制。
JSONObject的主要成员变量
//版本标识
private static final long serialVersionUID = 1L;
//默认初始容量
private static final int DEFAULT_INITIAL_CAPACITY = 16;
//用于存储的的容器,JSONObject常用的两种类型,LinkedHashMap(有序)和HashMap类型
private final Map<String, Object> map;
JSONObject的构造器
public JSONObject() {
this(16, false);
}
public JSONObject(Map<String, Object> map) {
if (map == null) {
throw new IllegalArgumentException("map is null.");
} else {
this.map = map;
}
}
public JSONObject(boolean ordered) {
this(16, ordered);
}
public JSONObject(int initialCapacity) {
this(initialCapacity, false);
}
//主要构造器,initialCapacity为容量,ordered为true时生成LinkedHashMap对象,为false时生成HashMap对象
public JSONObject(int initialCapacity, boolean ordered) {
if (ordered) {
this.map = new LinkedHashMap(initialCapacity);
} else {
this.map = new HashMap(initialCapacity);
}
}
最重要的构造器是public JSONObject(int initialCapacity, boolean ordered),其他构造器都直接调用此构造器。initialCapacity为初始容量,ordered为map是否有序
JSONObject的主要成员方法
//获取容量大小
public int size() {
return this.map.size();
}
//判断是否为空
public boolean isEmpty() {
return this.map.isEmpty();
}
//判断是否包含该键值
public boolean containsKey(Object key) {
return this.map.containsKey(key);
}
//判断是否包含该对象数据
public boolean containsValue(Object value) {
return this.map.containsValue(value);
}
//根据键值获了Object
public Object get(Object key) {
Object val = this.map.get(key);
if (val == null && key instanceof Number) {
val = this.map.get(key.toString());
}
return val;
}
//根据键值获了JSONObject
public JSONObject getJSONObject(String key) {
Object value = this.map.get(key);
if (value instanceof JSONObject) {
return (JSONObject)value;
} else if (value instanceof Map) {
return new JSONObject((Map)value);
} else {
return value instanceof String ? JSON.parseObject((String)value) : (JSONObject)toJSON(value);
}
}
//根据键值获取JSON数组
public JSONArray getJSONArray(String key) {
Object value = this.map.get(key);
if (value instanceof JSONArray) {
return (JSONArray)value;
} else if (value instanceof List) {
return new JSONArray((List)value);
} else {
return value instanceof String ? (JSONArray)JSON.parse((String)value) : (JSONArray)toJSON(value);
}
}
//getObject重载函数1:根据键值与类名获取对象
public <T> T getObject(String key, Class<T> clazz) {
Object obj = this.map.get(key);
return TypeUtils.castToJavaBean(obj, clazz);
}
//getObject重载函数2:根据键值与类型获取对象
public <T> T getObject(String key, Type type) {
Object obj = this.map.get(key);
return TypeUtils.cast(obj, type, ParserConfig.getGlobalInstance());
}
//getObject重载函数3:根据键值与类型引用获取对象
public <T> T getObject(String key, TypeReference typeReference) {
Object obj = this.map.get(key);
return typeReference == null ? obj : TypeUtils.cast(obj, typeReference.getType(), ParserConfig.getGlobalInstance());
}
根据键值获取各种不同类型的值:主要有以下类型Boolean/boolean,byte[]/Byte,Short/short,Integer/int,Long/long,Float/float,Double/double,BigDecimal,BigInteger,String,Date,java.sql.Date,java.sql.Timestamp
public Boolean getBoolean(String key) {
Object value = this.get(key);
return value == null ? null : TypeUtils.castToBoolean(value);
}
public byte[] getBytes(String key) {
Object value = this.get(key);
return value == null ? null : TypeUtils.castToBytes(value);
}
//以下代码省略
.......
类似于Map操作的增删改查
public Object put(String key, Object value) {
return this.map.put(key, value);
}
public JSONObject fluentPut(String key, Object value) {
this.map.put(key, value);
return this;
}
public void putAll(Map<? extends String, ? extends Object> m) {
this.map.putAll(m);
}
public JSONObject fluentPutAll(Map<? extends String, ? extends Object> m) {
this.map.putAll(m);
return this;
}
public void clear() {
this.map.clear();
}
public JSONObject fluentClear() {
this.map.clear();
return this;
}
public Object remove(Object key) {
return this.map.remove(key);
}
public JSONObject fluentRemove(Object key) {
this.map.remove(key);
return this;
}
转化为JAVA对象
//toJavaObject重载函数1
public <T> T toJavaObject(Class<T> clazz) {
if (clazz == Map.class) {
return this;
} else {
return clazz == Object.class && !this.containsKey(JSON.DEFAULT_TYPE_KEY) ? this : TypeUtils.castToJavaBean(this, clazz, ParserConfig.getGlobalInstance());
}
}
//toJavaObject重载函数2
public <T> T toJavaObject(Class<T> clazz, ParserConfig config, int features) {
if (clazz == Map.class) {
return this;
} else {
return clazz == Object.class && !this.containsKey(JSON.DEFAULT_TYPE_KEY) ? this : TypeUtils.castToJavaBean(this, clazz, config);
}
}
其他方法
//去重
public Set<String> keySet() {
return this.map.keySet();
}
//collection集合对象
public Collection<Object> values() {
return this.map.values();
}
//可用于迭代返回所有元素
public Set<Entry<String, Object>> entrySet() {
return this.map.entrySet();
}
//克隆
public Object clone() {
return new JSONObject((Map)(this.map instanceof LinkedHashMap ? new LinkedHashMap(this.map) : new HashMap(this.map)));
}
//相等判断
public boolean equals(Object obj) {
return this.map.equals(obj);
}
//hash值
public int hashCode() {
return this.map.hashCode();
}
实际应用
//发送请求,返回字符串,并将字符串转成JSONObject
String str = WeChatUtil.httpRequest(url, "GET", null);
JSONObject jsonObject = JSONObject.parseObject(str);
...
//根据键值"errocode"获取Object对象值
Object errCode = jsonObject.get("errcode");
...
//将wxUserDTO对象转化为字符串
String userInfo = JSONObject.toJSONString(wxUserDTO);
...