JSON的常用总结
1.Json-lib
项目地址:json-lib.sourceforge.net/index.html
json-lib最开始的也是应用最广泛的json解析工具,json-lib 不好的地方确实是依赖于很多第三方包,对于复杂类型的转换,json-lib对于json转换成bean还有缺陷, 比如一个类里面会出现另一个类的list或者map集合,json-lib从json到bean的转换就会出现问题。json-lib在功能和性能上面都不能满足现在互联网化的需求。
Maven 依赖
点击查看代码
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
点击查看代码
public static void main(String[] args) throws IOException, InterruptedException {
String json = ApiService.getApi();
JSONObject jsonObject = JSONObject.fromObject(json);
String city = JSONObject.fromObject(jsonObject.get("cityInfo")).get("city").toString();
JSONArray jsonArray = JSONObject.fromObject(jsonObject.get("data")).getJSONArray("forecast");
List<weather> weathers =new ArrayList<>();
System.out.println(jsonArray.size());
for (int i =0;i<jsonArray.size();i++){
//转实体类
weather weather = (weather)JSONObject.toBean((JSONObject) jsonArray.get(i), weather.class);
weathers.add(weather);
}
System.out.println(city);
weathers.forEach(e->{
System.out.println(e);
});
}
2.Gson
项目地址:github.com/google/gson
Gson是目前功能最全的Json解析神器,Gson当初是为因应Google公司内部需求而由Google自行研发而来,但自从在2008年五月公开发布第一版后已被许多公司或用户应用。 Gson的应用主要为toJson与fromJson两个转换函数,无依赖,不需要例外额外的jar,能够直接跑在JDK上。 在使用这种对象转换之前,需先创建好对象的类型以及其成员才能成功的将JSON字符串成功转换成相对应的对象。 类里面只要有get和set方法,Gson完全可以实现复杂类型的json到bean或bean到json的转换,是JSON解析的神器。
Maven 依赖
点击查看代码
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
点击查看代码
public static void main(String[] args) throws IOException, InterruptedException {
Gson gson = new Gson();
List<weather> json = ApiService.GetList();
String toJson = gson.toJson(json);
System.out.println("List转json:"+toJson);
List<weather> weathers=gson.fromJson(toJson, new TypeToken<List<weather>>() {}.getType());
System.out.println("json转List:"+weathers);
}
关于FastJson漏洞
fastjson 当前版本为 1.2.68 发布于 3 月底,日前某安全运营中心监测到,fastjson <= 1.2.68 版本存在远程代码执行漏洞,漏洞被利用可直接获取服务器权限。360CERT 将漏洞等级定为“高危 Maven 依赖
点击查看代码
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.72</version>
</dependency>
点击查看代码
public class FastJson {
public static void main(String[] args) throws IOException, InterruptedException {
String json = ApiService.getApi();
JSONObject jsonObject = JSONObject.parseObject(json);
Object data = jsonObject.get("data");
String toJSONString = JSON.toJSONString(data);
JSONArray jsonArray = JSONObject.parseObject(toJSONString).getJSONArray("forecast");
List<weather> weathers = JSON.parseArray(JSON.toJSONString(jsonArray), weather.class);
weathers.forEach(o->{
System.out.println(o);
});
}
}
点击查看代码
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
点击查看代码
public class JackJson {
public static void main(String[] args) throws IOException, InterruptedException {
List<weather> json = ApiService.GetList();
weather weather = json.get(0);
System.out.println("对象转json:"+JsonUtils.toJsonWithDefaultPrettyPrinter(weather));
Map<String,Object> map =new HashMap<>();
map.put("1","上海");
map.put("2","北京");
map.put("3","天津");
map.put("4","深圳");
Map<String,Object> map1 =new HashMap<>();
map1.put("city",map);
Map<String, Object> objectMap = JsonUtils.removeMapEmptyValue(map);
System.out.println("Map转json:"+objectMap);
String jsonTow = JsonUtils.toJsonWithDefaultPrettyPrinter(map1);
System.out.println("Map嵌套转json"+jsonTow);
}
}
JsonUtils工具类
public class JsonUtils {
private static final ObjectMapper mapper;
private JsonUtils() {
}
static {
mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
public static final String toJson(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (Throwable e) {
e.printStackTrace();
}
return "";
}
public static final String toJsonWithDefaultPrettyPrinter(Object obj) {
try {
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (Throwable e) {
e.printStackTrace();
}
return "";
}
public static final <T> T fromJson(final String json, Class<T> clazz) {
try {
return mapper.readValue(json, clazz);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public static final <T> T fromJson(final String json, JavaType type) {
try {
return mapper.readValue(json, type);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public static final <T> T fromJson(final String json, TypeReference<T> reference) {
try {
return mapper.readValue(json, reference);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public static final Map<String, Object> fromJson(final String json) {
return fromJson(json, Map.class);
}
public static Map<String, Object> removeMapEmptyValue(Map<String, Object> paramMap) {
Set<String> set = paramMap.keySet();
Iterator<String> it = set.iterator();
List<String> listKey = new ArrayList<String>();
while (it.hasNext()) {
String str = it.next();
if (paramMap.get(str) == null || "".equals(paramMap.get(str))) {
listKey.add(str);
}
}
for (String key : listKey) {
paramMap.remove(key);
}
return paramMap;
}
}
spring中直接初始配置jackjson
点击查看代码
spring:
jackson:
#日期类型格式化
date-format: yyyy-MM-dd HH:mm:ss
serialization:
#格式化输出,通常为了节省网络流量设置为false。因为格式化之后会带有缩进,方便阅读。
indent_output: false
#某些类对象无法序列化的时候,是否报错
fail_on_empty_beans: false
#设置空如何序列化,见下文代码方式详解
defaultPropertyInclusion: NON_EMPTY
deserialization:
#对象json中有不存在的属性时候,是否报错
fail_on_unknown_properties: false
parser:
#允许出现特殊字符和转义符
allow_unquoted_control_chars: true
#允许出现单引号
allow_single_quotes: true
点击查看代码
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder)
{
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
// Include.Include.ALWAYS 默认
// Include.NON_DEFAULT 属性为默认值不序列化
// Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
// Include.NON_NULL 属性为NULL 不序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 允许出现特殊字符和转义符
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
// 允许出现单引号
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
// 字段保留,将null值转为""
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
{
@Override
public void serialize(Object o, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException
{
jsonGenerator.writeString("");
}
});
return objectMapper;
}
https://www.jianshu.com/p/96a21c971adc
摘抄自:
作者:新一代程序员
链接:https://juejin.cn/post/7060888543912001572
来源:稀土掘金