Java-Class-I:com.alibaba.fastjson.JSONObject
| ylbtech-Java-Class-I:com.alibaba.fastjson.JSONObject |
| 1.返回顶部 |
1.1、
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
1.2、
String objJSON = "{'key':'value'}";
JSONObject responseObj = JSON.parseObject(objJSON);
String key = responseObj.getString("key");
2、
| 2.返回顶部 |
| 3.返回顶部 |
| 4.返回顶部 |
/*
* 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.
*/
package com.alibaba.fastjson; import static com.alibaba.fastjson.util.TypeUtils.castToBigDecimal;
import static com.alibaba.fastjson.util.TypeUtils.castToBigInteger;
import static com.alibaba.fastjson.util.TypeUtils.castToBoolean;
import static com.alibaba.fastjson.util.TypeUtils.castToByte;
import static com.alibaba.fastjson.util.TypeUtils.castToBytes;
import static com.alibaba.fastjson.util.TypeUtils.castToDate;
import static com.alibaba.fastjson.util.TypeUtils.castToDouble;
import static com.alibaba.fastjson.util.TypeUtils.castToFloat;
import static com.alibaba.fastjson.util.TypeUtils.castToInt;
import static com.alibaba.fastjson.util.TypeUtils.castToLong;
import static com.alibaba.fastjson.util.TypeUtils.castToShort;
import static com.alibaba.fastjson.util.TypeUtils.castToSqlDate;
import static com.alibaba.fastjson.util.TypeUtils.castToTimestamp; import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set; import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.util.TypeUtils; /**
* @author wenshao[szujobs@hotmail.com]
*/
public class JSONObject extends JSON implements Map<String, Object>, Cloneable, Serializable, InvocationHandler { private static final long serialVersionUID = 1L;
private static final int DEFAULT_INITIAL_CAPACITY = 16; private final Map<String, Object> map; public JSONObject(){
this(DEFAULT_INITIAL_CAPACITY, false);
} public JSONObject(Map<String, Object> map){
if (map == null) {
throw new IllegalArgumentException("map is null.");
}
this.map = map;
} public JSONObject(boolean ordered){
this(DEFAULT_INITIAL_CAPACITY, ordered);
} public JSONObject(int initialCapacity){
this(initialCapacity, false);
} public JSONObject(int initialCapacity, boolean ordered){
if (ordered) {
map = new LinkedHashMap<String, Object>(initialCapacity);
} else {
map = new HashMap<String, Object>(initialCapacity);
}
} public int size() {
return map.size();
} public boolean isEmpty() {
return map.isEmpty();
} public boolean containsKey(Object key) {
return map.containsKey(key);
} public boolean containsValue(Object value) {
return map.containsValue(value);
} public Object get(Object key) {
Object val = map.get(key); if (val == null && key instanceof Number) {
val = map.get(key.toString());
} return val;
} public JSONObject getJSONObject(String key) {
Object value = map.get(key); if (value instanceof JSONObject) {
return (JSONObject) value;
} if (value instanceof String) {
return JSON.parseObject((String) value);
} return (JSONObject) toJSON(value);
} public JSONArray getJSONArray(String key) {
Object value = map.get(key); if (value instanceof JSONArray) {
return (JSONArray) value;
} if (value instanceof String) {
return (JSONArray) JSON.parse((String) value);
} return (JSONArray) toJSON(value);
} public <T> T getObject(String key, Class<T> clazz) {
Object obj = map.get(key);
return TypeUtils.castToJavaBean(obj, clazz);
} public <T> T getObject(String key, Type type) {
Object obj = map.get(key);
return TypeUtils.cast(obj, type, ParserConfig.getGlobalInstance());
} public <T> T getObject(String key, TypeReference typeReference) {
Object obj = map.get(key);
if (typeReference == null) {
return (T) obj;
}
return TypeUtils.cast(obj, typeReference.getType(), ParserConfig.getGlobalInstance());
} public Boolean getBoolean(String key) {
Object value = get(key); if (value == null) {
return null;
} return castToBoolean(value);
} public byte[] getBytes(String key) {
Object value = get(key); if (value == null) {
return null;
} return castToBytes(value);
} public boolean getBooleanValue(String key) {
Object value = get(key); Boolean booleanVal = castToBoolean(value);
if (booleanVal == null) {
return false;
} return booleanVal.booleanValue();
} public Byte getByte(String key) {
Object value = get(key); return castToByte(value);
} public byte getByteValue(String key) {
Object value = get(key); Byte byteVal = castToByte(value);
if (byteVal == null) {
return 0;
} return byteVal.byteValue();
} public Short getShort(String key) {
Object value = get(key); return castToShort(value);
} public short getShortValue(String key) {
Object value = get(key); Short shortVal = castToShort(value);
if (shortVal == null) {
return 0;
} return shortVal.shortValue();
} public Integer getInteger(String key) {
Object value = get(key); return castToInt(value);
} public int getIntValue(String key) {
Object value = get(key); Integer intVal = castToInt(value);
if (intVal == null) {
return 0;
} return intVal.intValue();
} public Long getLong(String key) {
Object value = get(key); return castToLong(value);
} public long getLongValue(String key) {
Object value = get(key); Long longVal = castToLong(value);
if (longVal == null) {
return 0L;
} return longVal.longValue();
} public Float getFloat(String key) {
Object value = get(key); return castToFloat(value);
} public float getFloatValue(String key) {
Object value = get(key); Float floatValue = castToFloat(value);
if (floatValue == null) {
return 0F;
} return floatValue.floatValue();
} public Double getDouble(String key) {
Object value = get(key); return castToDouble(value);
} public double getDoubleValue(String key) {
Object value = get(key); Double doubleValue = castToDouble(value);
if (doubleValue == null) {
return 0D;
} return doubleValue.doubleValue();
} public BigDecimal getBigDecimal(String key) {
Object value = get(key); return castToBigDecimal(value);
} public BigInteger getBigInteger(String key) {
Object value = get(key); return castToBigInteger(value);
} public String getString(String key) {
Object value = get(key); if (value == null) {
return null;
} return value.toString();
} public Date getDate(String key) {
Object value = get(key); return castToDate(value);
} public java.sql.Date getSqlDate(String key) {
Object value = get(key); return castToSqlDate(value);
} public java.sql.Timestamp getTimestamp(String key) {
Object value = get(key); return castToTimestamp(value);
} public Object put(String key, Object value) {
return map.put(key, value);
} public JSONObject 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 void clear() {
map.clear();
} public JSONObject fluentClear() {
map.clear();
return this;
} public Object remove(Object key) {
return map.remove(key);
} public JSONObject fluentRemove(Object key) {
map.remove(key);
return this;
} public Set<String> keySet() {
return map.keySet();
} public Collection<Object> values() {
return map.values();
} public Set<Map.Entry<String, Object>> entrySet() {
return map.entrySet();
} @Override
public Object clone() {
return new JSONObject(map instanceof LinkedHashMap //
? new LinkedHashMap<String, Object>(map) //
: new HashMap<String, Object>(map)
);
} public boolean equals(Object obj) {
return this.map.equals(obj);
} public int hashCode() {
return this.map.hashCode();
} public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
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);
return TypeUtils.cast(value, method.getGenericReturnType(), ParserConfig.getGlobalInstance());
} throw new UnsupportedOperationException(method.toGenericString());
} public Map<String, Object> getInnerMap() {
return this.map;
} private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
SecureObjectInputStream.ensureFields();
if (SecureObjectInputStream.fields != null && !SecureObjectInputStream.fields_error) {
ObjectInputStream secIn = new SecureObjectInputStream(in);
try {
secIn.defaultReadObject();
return;
} catch (java.io.NotActiveException e) {
// skip
}
} in.defaultReadObject();
for (Entry entry : map.entrySet()) {
final Object key = entry.getKey();
if (key != null) {
ParserConfig.global.checkAutoType(key.getClass());
} final Object value = entry.getValue();
if (value != null) {
ParserConfig.global.checkAutoType(value.getClass());
}
}
} static class SecureObjectInputStream extends ObjectInputStream {
static Field[] fields;
static volatile boolean fields_error; static void ensureFields() {
if (fields == null && !fields_error) {
try {
final Field[] declaredFields = ObjectInputStream.class.getDeclaredFields();
String[] fieldnames = new String[]{"bin", "passHandle", "handles", "curContext"};
Field[] array = new Field[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) throws IOException {
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)
throws IOException, ClassNotFoundException {
String name = desc.getName();
if (name.length() > 2) {
int index = name.lastIndexOf('[');
if (index != -1) {
name = name.substring(index + 1);
}
if (name.length() > 2 && name.charAt(0) == 'L' && name.charAt(name.length() - 1) == ';') {
name = name.substring(1, name.length() - 1);
}
ParserConfig.global.checkAutoType(name, null);
}
return super.resolveClass(desc);
} protected Class<?> resolveProxyClass(String[] interfaces)
throws IOException, ClassNotFoundException {
for (String interfacename : interfaces) {
//检查是否处于黑名单
ParserConfig.global.checkAutoType(interfacename, null);
}
return super.resolveProxyClass(interfaces);
} //Hack:默认构造方法会调用这个方法,重写此方法使用反射还原部分关键属性
protected void readStreamHeader() throws IOException, StreamCorruptedException { }
}
}
| 5.返回顶部 |
| 6.返回顶部 |
![]() |
作者:ylbtech 出处:http://ylbtech.cnblogs.com/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 |
Java-Class-I:com.alibaba.fastjson.JSONObject的更多相关文章
- 42-字符串到json 的错误 com.alibaba.fastjson.JSONObject cannot be cast to java.lang.String
json: {"updated_at":1551780617,"attr":{"uptime_h":3,"uptime_m&quo ...
- com.alibaba.fastjson.JSONObject;的使用
转: com.alibaba.fastjson.JSONObject;的使用 2018-11-04 23:51:23 mameng1998 阅读数 6404更多 分类专栏: java 1 POM ...
- java后台接收json数据,报错com.alibaba.fastjson.JSONObject cannot be cast to xxx
从前台接收json封装的list数据,在后台接收时一直报错,com.alibaba.fastjson.JSONObject cannot be cast to xxx, 使用这种方式接收可以接收 @R ...
- 探索RequestBody报com.alibaba.fastjson.JSONObject cannot be cast to xxx
今天使用RequestBody接受前端传过来的参数,以前接受字符串数组非常成功,这次把形参改成了List<User>,原本以为顺利接受参数并映射成User的list结构,结果竟然在我取us ...
- net.sf.json.JSONOBJECT.fromObject 与 com.alibaba.fastjson.JSONObject.parseObject
文章待补充,先写写以下知识点好了. NULL值处理之 net.sf.json.JSONObject 和 com.alibaba.fastjson.JSONObject区别 JSON作为一个轻量级的文本 ...
- com.alibaba.fastjson.JSONObject之对象与JSON转换方法
com.alibaba.fastjson.JSONObject时经常会用到它的转换方法,包括Java对象转成JSON串.JSON对象,JSON串转成java对象.JSON对象,JSON对象转换Java ...
- com.alibaba.fastjson.JSONObject
package com.alibaba.fastjson; import java.util.Date; import java.util.List; import com.alibaba.fastj ...
- No message body writer has been found for class com.alibaba.fastjson.JSONObject, ContentType: */*
1:当使用 cxf 发布服务时,要求返回值类型为xml,或者json等 @Path("/searchProductByText") @GET @Produces({"ap ...
- com.alibaba.fastjson.JSONObject循环给同一对象赋值会出现"$ref":"$[0]"现象问题
1.今天定义了一个JSONObject对象,引用的com.alibaba.fastjson.JSONObject,循环给这个对象赋值出现"$ref":"$[0]" ...
随机推荐
- 八年技术加持,性能提升10倍,阿里云HBase 2.0首发商用
摘要: 早在2010年开始,阿里巴巴集团开始研究并把HBase投入生产环境使用,从最初的淘宝历史交易记录,到蚂蚁安全风控数据存储,HBase在几代阿里专家的不懈努力下,已经表现得运行更稳定.性能更高效 ...
- Yii2 使用十一 在设置enablePrettyUrl时候,defaultAction的设置方法
启用美化Url的功能 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'enableS ...
- LOJ6485 LJJ 学二项式定理 解题报告
LJJ 学二项式定理 题意 \(T\)组数据,每组给定\(n,s,a_0,a_1,a_2,a_3\),求 \[ \sum_{i=0}^n \binom{n}{i}s^ia_{i\bmod 4} \] ...
- Delphi实现程序只运行一次并激活已打开的程序
我们的程序有时候只允许运行一次,并且最好的情况是,如果程序第二次运行,就激活原来的程序.网上有很多的方法实现程序只运行一次,但对于激活原来的窗口却都不怎么好.关键就在于激活原来的程序,一般的做法是在工 ...
- python 拆分字符串(3.0)
拆分字符串 1. def my_split(s, ds): l = [s] for d in ds: res = [] list(map(lambda x: res.extend(x.split(d) ...
- Win7下使用DbgPrint
在Win7下默认DbgPrint输出信息后,使用DbgView看不到内容. 新建一个reg文件,双击导出就行了. Windows Registry Editor Version 5.00 [HKEY_ ...
- Awesome Adb——一份超全超详细的 ADB 用法大全
https://github.com/mzlogin/awesome-adb https://www.cnblogs.com/bravesnail/articles/5850335.html ...
- PAT_A1103#Integer Factorization
Source: PAT A1103 Integer Factorization (30 分) Description: The K−P factorization of a positive inte ...
- 前端(七)—— 盒模型之display、overflow、隐藏、border、margin、样式支持,层级结构
display.overflow.隐藏.border.margin.样式支持,层级结构 一.盒模型之display 1.三种样式 block 块 inline 内联/行内 inline-block 内 ...
- <随便写>数据库调优的几种方式
1.创建索引 要尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引 在经常需要进行检索的字段上创建索引,比如要按照表字段username进行检索,那么就应该在姓名字段 ...
