FastJson&Jaskson使用对比

160 阅读2分钟

背景

工作中很多同事都了解这两个Jar包的存在,但是使用的时候,都是通过前辈同事封装好的工具类。要么输出一个Json string,要么序列化为对应的对象,或者数组对象。本文就是基于此,做一个api的颗粒度澄清,希望本文能让读者更加的明白两者的使用和区别。

反序列化

反序列化指的是把某一个json字符串,序列化成Java对象或者数组

1. 序列号为对象

String json = "{\n" +
        "    \"age\": 11,\n" +
        "    \"name\": \"胡哥\"\n" +
        "}";


// 反序列化--> Object
// jackSon
ObjectMapper objectMapper = new ObjectMapper();
try {
    User user = objectMapper.readValue(json, User.class);
    System.out.println("objectMapper:" + user);
} catch (JsonProcessingException e) {
    throw new RuntimeException(e);
}
// fastjson
User user = JSON.parseObject(json, User.class);
System.out.println("fastJson:" + user);

输出为:

objectMapper:JacksonVsFastJson.User(age=11, name=胡哥)
fastJson:JacksonVsFastJson.User(age=11, name=胡哥)

2. 序列化为数组

// 反序列化-- list
String arrJson = "[\n" +
        "    {\n" +
        "        \"age\": 11,\n" +
        "        \"name\": \"胡哥\"\n" +
        "    },\n" +
        "    {\n" +
        "        \"age\": 22,\n" +
        "        \"name\": \"胡哥2\"\n" +
        "    }\n" +
        "]";
ObjectMapper arrayMapper = new ObjectMapper();
try {
    List<User> users = arrayMapper.readValue(arrJson, new TypeReference<List<User>>() {
    });
    System.out.println("jackSon parse array:" + users);
} catch (JsonProcessingException e) {
    throw new RuntimeException(e);
}

List<User> users = JSON.parseArray(arrJson, User.class);
System.out.println("fastJson parse array:" + users);

序列化

fastjson序列化

JSON.toJSONString(user)

jackson序列化

new ObjectMapper().writeValueAsString()

FastJson内置json对象

FastJson只有两种内置Json对象。

如果一个json字符串以[]开头,那么就是一个JSONArray对象。

其他都是JSONObject对象

所以我们可以基于此,通过json对象去获取任意层级的JSON数据。

{
    "array":[
        {
            "apple":{
                "age":1,
                "isBool":false,
                
            }
        }
    ]
}
JSONObject object = JSON.parseObject(jsonLevelStr);
Integer age = object.getJSONArray("array").getJSONObject(0).getJSONObject("apple").getInteger("age");

获取age的方式。先变成JSONObject然后获取JSONArray,拿到第0个,最后依次遍历Object

Jackson的几种内置Json对象抽象

ArrayNode: 代表一个数组对象 ObjectNode: 代表一个对象 ValueNode: 代表ObjectNode的Value

ArrayNode和ObjectNode属于同一个父类,抽象为ContainerNode,代表了一个对象的容器。 通过下标或者字段名拿到的属于是ValueObject image.png 我们的值对象常见的通常为3种,NumberNode,BooleanNode,TextNode。 所以我们可以通过上面那个例子,用Jackson获取。

ObjectMapper obj = new ObjectMapper();
JsonNode jsonNode = obj.readTree(jsonStr);
int age = jsonNode.get("array").get(0).get("apple").get("age").asInt();

总结

Jaskson和Fastjson在使用上几乎没啥大的区别,主要弄清楚它的几种内置对象对应的Json字符串的抽象即可灵活的使用。另外支持的特性,比如大小写,驼峰,别名,序列化形式等等其他特性不在本文的讨论范围之内。