/** Copyright 1999-2017 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*http://www.apache.org/licenses/LICENSE-2.0*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.*/
packagecom.alibaba.fastjson;import staticcom.alibaba.fastjson.util.TypeUtils.castToBigDecimal;import staticcom.alibaba.fastjson.util.TypeUtils.castToBigInteger;import staticcom.alibaba.fastjson.util.TypeUtils.castToBoolean;import staticcom.alibaba.fastjson.util.TypeUtils.castToByte;import staticcom.alibaba.fastjson.util.TypeUtils.castToBytes;import staticcom.alibaba.fastjson.util.TypeUtils.castToDate;import staticcom.alibaba.fastjson.util.TypeUtils.castToDouble;import staticcom.alibaba.fastjson.util.TypeUtils.castToFloat;import staticcom.alibaba.fastjson.util.TypeUtils.castToInt;import staticcom.alibaba.fastjson.util.TypeUtils.castToLong;import staticcom.alibaba.fastjson.util.TypeUtils.castToShort;import staticcom.alibaba.fastjson.util.TypeUtils.castToSqlDate;import staticcom.alibaba.fastjson.util.TypeUtils.castToTimestamp;import java.io.*;importjava.lang.reflect.Field;importjava.lang.reflect.InvocationHandler;importjava.lang.reflect.Method;importjava.lang.reflect.Type;importjava.math.BigDecimal;importjava.math.BigInteger;importjava.util.Collection;importjava.util.Date;importjava.util.HashMap;importjava.util.LinkedHashMap;importjava.util.Map;importjava.util.Set;importcom.alibaba.fastjson.annotation.JSONField;importcom.alibaba.fastjson.parser.ParserConfig;importcom.alibaba.fastjson.util.TypeUtils;/***@authorwenshao[szujobs@hotmail.com]*/
public class JSONObject extends JSON implements Map, Cloneable, Serializable, InvocationHandler {private static final long serialVersionUID = 1L;private static final int DEFAULT_INITIAL_CAPACITY = 16;private final Mapmap;publicJSONObject(){this(DEFAULT_INITIAL_CAPACITY, false);
}public JSONObject(Mapmap){if (map == null) {throw new IllegalArgumentException("map is null.");
}this.map =map;
}public JSONObject(booleanordered){this(DEFAULT_INITIAL_CAPACITY, ordered);
}public JSONObject(intinitialCapacity){this(initialCapacity, false);
}public JSONObject(int initialCapacity, booleanordered){if(ordered) {
map= new LinkedHashMap(initialCapacity);
}else{
map= new HashMap(initialCapacity);
}
}public intsize() {returnmap.size();
}public booleanisEmpty() {returnmap.isEmpty();
}public booleancontainsKey(Object key) {returnmap.containsKey(key);
}public booleancontainsValue(Object value) {returnmap.containsValue(value);
}publicObject get(Object key) {
Object val=map.get(key);if (val == null && key instanceofNumber) {
val=map.get(key.toString());
}returnval;
}publicJSONObject getJSONObject(String key) {
Object value=map.get(key);if (value instanceofJSONObject) {return(JSONObject) value;
}if (value instanceofString) {returnJSON.parseObject((String) value);
}return(JSONObject) toJSON(value);
}publicJSONArray getJSONArray(String key) {
Object value=map.get(key);if (value instanceofJSONArray) {return(JSONArray) value;
}if (value instanceofString) {return(JSONArray) JSON.parse((String) value);
}return(JSONArray) toJSON(value);
}public T getObject(String key, Classclazz) {
Object obj=map.get(key);returnTypeUtils.castToJavaBean(obj, clazz);
}public T getObject(String key, Type type) {
Object obj=map.get(key);returnTypeUtils.cast(obj, type, ParserConfig.getGlobalInstance());
}public T getObject(String key, TypeReference typeReference) {
Object obj=map.get(key);if (typeReference == null) {return(T) obj;
}returnTypeUtils.cast(obj, typeReference.getType(), ParserConfig.getGlobalInstance());
}publicBoolean getBoolean(String key) {
Object value=get(key);if (value == null) {return null;
}returncastToBoolean(value);
}public byte[] getBytes(String key) {
Object value=get(key);if (value == null) {return null;
}returncastToBytes(value);
}public booleangetBooleanValue(String key) {
Object value=get(key);
Boolean booleanVal=castToBoolean(value);if (booleanVal == null) {return false;
}returnbooleanVal.booleanValue();
}publicByte getByte(String key) {
Object value=get(key);returncastToByte(value);
}public bytegetByteValue(String key) {
Object value=get(key);
Byte byteVal=castToByte(value);if (byteVal == null) {return 0;
}returnbyteVal.byteValue();
}publicShort getShort(String key) {
Object value=get(key);returncastToShort(value);
}public shortgetShortValue(String key) {
Object value=get(key);
Short shortVal=castToShort(value);if (shortVal == null) {return 0;
}returnshortVal.shortValue();
}publicInteger getInteger(String key) {
Object value=get(key);returncastToInt(value);
}public intgetIntValue(String key) {
Object value=get(key);
Integer intVal=castToInt(value);if (intVal == null) {return 0;
}returnintVal.intValue();
}publicLong getLong(String key) {
Object value=get(key);returncastToLong(value);
}public longgetLongValue(String key) {
Object value=get(key);
Long longVal=castToLong(value);if (longVal == null) {return 0L;
}returnlongVal.longValue();
}publicFloat getFloat(String key) {
Object value=get(key);returncastToFloat(value);
}public floatgetFloatValue(String key) {
Object value=get(key);
Float floatValue=castToFloat(value);if (floatValue == null) {return0F;
}returnfloatValue.floatValue();
}publicDouble getDouble(String key) {
Object value=get(key);returncastToDouble(value);
}public doublegetDoubleValue(String key) {
Object value=get(key);
Double doubleValue=castToDouble(value);if (doubleValue == null) {return0D;
}returndoubleValue.doubleValue();
}publicBigDecimal getBigDecimal(String key) {
Object value=get(key);returncastToBigDecimal(value);
}publicBigInteger getBigInteger(String key) {
Object value=get(key);returncastToBigInteger(value);
}publicString getString(String key) {
Object value=get(key);if (value == null) {return null;
}returnvalue.toString();
}publicDate getDate(String key) {
Object value=get(key);returncastToDate(value);
}publicjava.sql.Date getSqlDate(String key) {
Object value=get(key);returncastToSqlDate(value);
}publicjava.sql.Timestamp getTimestamp(String key) {
Object value=get(key);returncastToTimestamp(value);
}publicObject put(String key, Object value) {returnmap.put(key, value);
}publicJSONObject fluentPut(String key, Object value) {
map.put(key, value);return this;
}public void putAll(Map extends String, ? extends Object>m) {
map.putAll(m);
}public JSONObject fluentPutAll(Map extends String, ? extends Object>m) {
map.putAll(m);return this;
}public voidclear() {
map.clear();
}publicJSONObject fluentClear() {
map.clear();return this;
}publicObject remove(Object key) {returnmap.remove(key);
}publicJSONObject fluentRemove(Object key) {
map.remove(key);return this;
}public SetkeySet() {returnmap.keySet();
}public Collectionvalues() {returnmap.values();
}public Set>entrySet() {returnmap.entrySet();
}
@OverridepublicObject clone() {return new JSONObject(map instanceof LinkedHashMap // ? new LinkedHashMap(map) // : new HashMap(map)
);
}public booleanequals(Object obj) {return this.map.equals(obj);
}public inthashCode() {return this.map.hashCode();
}public Object invoke(Object proxy, Method method, Object[] args) throwsThrowable {
Class>[] parameterTypes =method.getParameterTypes();if (parameterTypes.length == 1) {if (method.getName().equals("equals")) {return this.equals(args[0]);
}
Class> returnType =method.getReturnType();if (returnType != void.class) {throw new JSONException("illegal setter");
}
String name= null;
JSONField annotation= method.getAnnotation(JSONField.class);if (annotation != null) {if (annotation.name().length() != 0) {
name=annotation.name();
}
}if (name == null) {
name=method.getName();if (!name.startsWith("set")) {throw new JSONException("illegal setter");
}
name= name.substring(3);if (name.length() == 0) {throw new JSONException("illegal setter");
}
name= Character.toLowerCase(name.charAt(0)) + name.substring(1);
}
map.put(name, args[0]);return null;
}if (parameterTypes.length == 0) {
Class> returnType =method.getReturnType();if (returnType == void.class) {throw new JSONException("illegal getter");
}
String name= null;
JSONField annotation= method.getAnnotation(JSONField.class);if (annotation != null) {if (annotation.name().length() != 0) {
name=annotation.name();
}
}if (name == null) {
name=method.getName();if (name.startsWith("get")) {
name= name.substring(3);if (name.length() == 0) {throw new JSONException("illegal getter");
}
name= Character.toLowerCase(name.charAt(0)) + name.substring(1);
}else if (name.startsWith("is")) {
name= name.substring(2);if (name.length() == 0) {throw new JSONException("illegal getter");
}
name= Character.toLowerCase(name.charAt(0)) + name.substring(1);
}else if (name.startsWith("hashCode")) {return this.hashCode();
}else if (name.startsWith("toString")) {return this.toString();
}else{throw new JSONException("illegal getter");
}
}
Object value=map.get(name);returnTypeUtils.cast(value, method.getGenericReturnType(), ParserConfig.getGlobalInstance());
}throw newUnsupportedOperationException(method.toGenericString());
}public MapgetInnerMap() {return this.map;
}private void readObject(final java.io.ObjectInputStream in) throwsIOException, ClassNotFoundException {
SecureObjectInputStream.ensureFields();if (SecureObjectInputStream.fields != null && !SecureObjectInputStream.fields_error) {
ObjectInputStream secIn= newSecureObjectInputStream(in);
secIn.defaultReadObject();return;
}
in.defaultReadObject();for(Entry entry : map.entrySet()) {final Object key =entry.getKey();if (key != null) {
ParserConfig.global.checkAutoType(key.getClass().getName(),null);
}final Object value =entry.getValue();if (value != null) {
ParserConfig.global.checkAutoType(value.getClass().getName(),null);
}
}
}static class SecureObjectInputStream extendsObjectInputStream {staticField[] fields;static volatile booleanfields_error;static voidensureFields() {if (fields == null && !fields_error) {try{final Field[] declaredFields = ObjectInputStream.class.getDeclaredFields();
String[] fieldnames= new String[]{"bin", "passHandle", "handles", "curContext"};
Field[] array= newField[fieldnames.length];for (int i = 0; i < fieldnames.length; i++) {
Field field=TypeUtils
.getField(ObjectInputStream.class, fieldnames[i]
, declaredFields
);
field.setAccessible(true);
array[i]=field;
}
fields=array;
}catch(Throwable error) {
fields_error= true;
}
}
}public SecureObjectInputStream(ObjectInputStream in) throwsIOException {super(in);try{for (int i = 0; i < fields.length; i++) {final Field field =fields[i];final Object value =field.get(in);
field.set(this, value);
}
}catch(IllegalAccessException e) {
fields_error= true;
}
}protected Class>resolveClass(ObjectStreamClass desc)throwsIOException, ClassNotFoundException {
String name=desc.getName();
ParserConfig.global.checkAutoType(name,null);return super.resolveClass(desc);
}protected Class>resolveProxyClass(String[] interfaces)throwsIOException, ClassNotFoundException {for(String interfacename : interfaces) {//检查是否处于黑名单
ParserConfig.global.checkAutoType(interfacename, null);
}return super.resolveProxyClass(interfaces);
}//Hack:默认构造方法会调用这个方法,重写此方法使用反射还原部分关键属性
protected void readStreamHeader() throwsIOException, StreamCorruptedException {
}
}
}