json解析库 fastjson gson jackson

2015-11-15 21:56:00
admin
原创 2272
摘要:json解析库 fastjson gson jackson

一、json介绍

官方介绍http://www.json.org

JSON (JavaScript Object Notation) is a lightweight data-interchange format.


JSON is built on two structures:集合和列表

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.


object,集合
{}
{ members }
members
pair
pair , members
pair
string : value

array,列表
[]
[ elements ]
elements
value 
value , elements
value
string
number
object
array
true
false
null


二、fastjson、gson、jackson解析库对比

fastjson,阿里巴巴开源json解析库,漏洞太多,不推荐使用;

gson,谷歌开源json解析库,目前引用量最大,推荐使用;

jackson,SpringBoot内置json解析库,依赖于SpringBoot生态目前引用量超过fastjson;


三、fastjson代码示例

1、解析可能抛异常需要捕获,因为是map所以元素不允许重复;

2、如果需要元素按插入顺序排序,需要在初始化时指定;

3、null和空字符串解析不会抛异常,会返回null对象;


import com.alibaba.fastjson.*;
import com.alibaba.fastjson.serializer.*;

public class JSONTest {
public static void main(String[] args) {

String content = "{}";
JSONObject obj = JSON.parseObject(content);
System.out.println(obj); //{}

obj = JSON.parseObject("{\"name\":\"feinen\"}");
System.out.println(obj.get("name"));
System.out.println(obj.get("unknown")); //返回null
System.out.println(obj.getString("unknown")); //返回null
System.out.println(obj.getIntValue("unknown")); //返回0
System.out.println(obj.toString()); //输出{"name":"feinen"}

obj = new JSONObject(true); 
obj.put("name", "xiangfeineng");
obj.put("age", null);
obj.put("friends", new JSONArray());
SerializerFeature[] features = { SerializerFeature.WriteMapNullValue };
String msg = JSON.toJSONString(obj, features);
System.out.println(msg); //输出{"name":"xiangfeineng","age":null,"friends":[]}
}
}


四、fastjson自定义序列化

浮点数序列化:JSONFilter.java


import com.alibaba.fastjson.*;
import com.alibaba.fastjson.serializer.*;


public class JSONFilter {
public static class MyValueFilter implements ValueFilter {
public Object process(Object object, String name, Object value) {
if (value != null && value instanceof Double) {
String str = value.toString();
if (str.endsWith(".0"))
str = str.substring(0, str.length() - 2);
else if (str.endsWith(".00"))
str = str.substring(0, str.length() - 3);
return str;
}
return value;
}
}


public static void main(String[] args) {
JSONObject json = new JSONObject(true);
json.put("double", 1.0);
System.out.println(JSON.toJSONString(json));
System.out.println(JSON.toJSONString(json, new MyValueFilter()));
System.out.println(json.get("double").getClass().getName());
}
}


输出:

{"double":1}
{"double":"1"}
java.lang.Double


五、gson使用详解

1、JsonElement包含4个子类:JsonObject、JsonArray、JsonPrimitive、JsonNull;

2、每种JsonElement都包含特定方法,使用isXX方法判断元素类型,使用getAs方法转换元素具体类型;

3、只有JsonPrimitive可以获取元素内容,getAsString和getAsInt都可以调用;

4、gson默认维护元素插入顺序;

5、JsonParser用于解析字符串到json对象,解析null抛出异常,解析空字符串返回null;

6、Gson类解析字符串到POJO对象,或者将POJO对象转换成字符串,解析null和空字符串不会抛异常,会返回null对象;

7、Gson类解析字符串到POJO对象是利用反射机制,字符串不包含任何POJO属性时,返回的POJO对象属性值都是null;

8、时间序列化调用GsonBuilder的setDateFormat("yyyy-MM-dd HH:mm:ss"),或者使用类型适配器,后者优先级更高;

9、transient申明的字段不序列化,excludeFieldsWithoutExposeAnnotation表示使用@Expose注解的字段才会序列化;

10、@SerializedName用于指定序列化字段名;

11、setPrettyPrinting设置优美序列化格式,serializeNulls设置序列化空对象;


使用类型适配器进行时间序列化:

import java.lang.reflect.*;
import com.google.gson.*;
import java.util.*;
import java.text.*;

public class DateSerializer implements JsonSerializer<Date> {
private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(df.format(src));
}
}


import java.lang.reflect.*;
import com.google.gson.*;
import java.util.*;
import java.text.*;

public class DateDeserializer implements JsonDeserializer<Date> {
private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
return df.parse(json.getAsString());
} catch (Exception e) {
throw new JsonParseException(e);
}
}
}


GsonBuilder设置类型适配器:

registerTypeAdapter(Date.class, new DateSerializer())

registerTypeAdapter(Date.class, new DateDeserializer())

发表评论
评论通过审核之后才会显示。