1、String转换为JsonObject
JSONObject resJson = JSONObject.parseObject(response);
2、获取嵌套的Json对象
JSONObject alipayResponse = resJson.getJSONObject("alipay_trade_precreate_response");
3、获取Json对象key对应的value
String sign = resJson.getString("sign");
4、fastjson序列化乱序问题
1)初始化为有序json对象
JSONObject jsonOrdered= new JSONObject(true);
2)将String对象转换过程中,不要调整顺序
JSONObject jsonOrdered = JSONObject.parseObject(jsonString, Feature.OrderedField);
PS:Feature.OrderedField作用是将String转换Json对象时不要调整顺序(fastJson转换时默认使用HashMap,所以排序规则是根据HASH值排序的)
5、fastjson不安全在哪里
(1)fastjson经常爆出有漏洞,那么到底是哪里有漏洞?
关键就是它的AutoType功能。fastjson会判断json字符串中@type标识,将json字符串转化为任意指定的java类
User.java
package others;
public class User {
private String name;
public User() {
System.out.println("com.server.User()");
}
public String getName() {
System.out.println("getName");
return name;
}
public void setName(String name) {
System.out.println("setName");
this.name = name;
}
}
例子1:
public static void main(String[] args) {
String x = "{\"name\": \"test\"}";
Object xx = JSON.parse(x);
System.out.println(xx instanceof User);
System.out.println(xx);
System.out.println();
}
输出:
false
{"name":"test"}
这里判断xx是否为User类类型,返回为false
例子2:如果强转会报错
public static void main(String[] args) {
String a = "{\"name\": \"test\"}";
User aa = (User) JSON.parse(a);
System.out.println(aa);
System.out.println();
}
输出:
Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to others.User
at others.FastjsonTest.main(FastjsonTest.java:9)
例子3:但是如果开启了AutoType功能,就能强转
public static void main(String[] args) {
// 启用autotype,注意这可能带来安全风险
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
String y = "{\"@type\":\"others.User\",\"name\": \"test\"}";
User yy = (User) JSON.parse(y);
System.out.println(yy);
System.out.println();
}
输出:
com.server.User()
setName
others.User@270421f5
例子4:正常使用
public static void main(String[] args) {
String z = "{\"name\": \"test\"}";
User zz = (User) JSON.parseObject(z, User.class);
System.out.println(zz);
}
6、如何避免漏洞
(1)可以选择fastjson noneautotype版本,它就没有这个功能了
(2)更新到最新版本,添加了黑白名单、修补逻辑漏洞
参考资料:
fastjson到底做错了什么?为什么会被频繁爆出漏洞? (baidu.com)
从漏洞挖掘角度分析fastjson1.2.80 Bypass-腾讯云开发者社区-腾讯云 (tencent.com)
又遇fastjson漏洞-腾讯云开发者社区-腾讯云 (tencent.com)