Home > Java > javaTutorial > body text

After comparing the three, I found that this JSON library is the best to use.

Release: 2023-07-26 17:12:06
forward
1748 people have browsed it

This article uses JMH to test the performance of several common JSON parsing libraries in Java. Every time I see others on the Internet saying how good the performance of a certain library is, crushing other libraries. But seeing is better than hearing. Only what you have tested yourself is the most trustworthy.

JSON is a very common data transmission format in both web development and server development. Generally speaking, we don’t need to be too concerned about the performance of JSON parsing construction unless it is In systems with relatively high performance requirements.

There are currently many open source

JSON class libraries for Java. Below we take 4 commonly used JSON libraries for performance testing and comparison, and analyze if based on the test results Choose the most appropriate JSON library according to the actual application scenario.

The four JSON class libraries are:

Gson, FastJson, Jackson, Json-lib.

Brief introduction

Choose a suitable JSON library to consider from many aspects:

  • String parsing into JSON performance

  • String parsing into JavaBean performance

  • JavaBean construction JSON performance

  • Collection construction JSON performance

  • Ease of use

Let’s briefly introduce the identity background of the four class libraries.

Gson

Project address: https://github.com/google/gson

Gson is currently the most versatile Json parsing artifact. Gson was originally developed by Google in response to Google's internal needs. However, since the first version was publicly released in May 2008, it has been Many companies or users apply.

The application of Gson mainly consists of two conversion functions: toJson and fromJson. It has no dependencies and does not require any additional jars. It can run directly on the JDK.

Before using this kind of object conversion, you need to create the object type and its members before you can successfully convert the JSON string into the corresponding object. As long as there are get and set methods in the class, Gson can completely convert complex types of json to bean or bean to json. It is an artifact of JSON parsing.

FastJson

Project address: https://github.com/alibaba/fastjson

Fastjson is a high-performance JSON processor written in Java language, developed by Alibaba. No dependencies, no need for extra jars, and can run directly on the JDK.

FastJson will have some problems when converting complex types of beans to Json. Reference types may appear, causing Json conversion errors, and references need to be specified. FastJson uses an original algorithm to increase the speed of parse to the extreme, surpassing all json libraries.

Jackson

Project address: https://github.com/FasterXML/jackson

Jackson is currently a widely used Java open source framework for serializing and deserializing json.

The Jackson community is relatively active and the update speed is relatively fast. According to statistics in Github, Jackson is one of the most popular json parsers and is the default json parser of Spring MVC. It's Jackson.

Jackson has many advantages:

  • Jackson relies on fewer jar packages and is simple and easy to use.

  • Compared with other Java json frameworks such as Gson, Jackson parses large json files faster.

  • Jackson takes up less memory when running and has better performance

  • Jackson is flexible The API can be easily extended and customized.

The latest version is 2.9.4. The core module of Jackson consists of three parts:

  • jackson-core core package provides related APIs based on "stream mode" parsing, which includes JsonPaser and JsonGenerator. Jackson's internal implementation generates and parses json through the high-performance streaming API's JsonGenerator and JsonParser.

  • jackson-annotations annotation package, providing standard annotation functions;

  • ##jackson-databind Data binding package, provides related APIs based on "Object Binding" parsing (ObjectMapper) and "Tree Model" parsing related APIs (JsonNode); APIs based on "Object Binding" parsing and "Tree Model" parsing API dependencies API based on "stream mode" parsing.

Json-lib

Project address: http://json-lib.sourceforge.net/index.html

json-lib is the earliest and most widely used json parsing tool. The disadvantage of json-lib is that it relies on many third-party packages. For complex type conversion, json-lib still has flaws in converting json into beans. For example, if a list or map collection of another class appears in a class, problems will arise in json-lib's conversion from json to beans. json-lib cannot meet the current Internet needs in terms of functionality and performance.

Writing performance tests

Next, start writing the performance test code for these four libraries.

Add maven dependencies

Of course, the first step is to add the maven dependencies of the four libraries. To be fair, I use their latest versions:

<!-- Json libs-->
<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.46</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.4</version>
</dependency>
Copy after login

Four library tool classes

FastJsonUtil.java

public class FastJsonUtil {
    public static String bean2Json(Object obj) {
        return JSON.toJSONString(obj);
    }

    public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
        return JSON.parseObject(jsonStr, objClass);
    }
}
Copy after login

GsonUtil.java

public class GsonUtil {
    private static Gson gson = new GsonBuilder().create();

    public static String bean2Json(Object obj) {
        return gson.toJson(obj);
    }

    public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
        return gson.fromJson(jsonStr, objClass);
    }

    public static String jsonFormatter(String uglyJsonStr) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(uglyJsonStr);
        return gson.toJson(je);
    }
}
Copy after login

JacksonUtil.java

public class JacksonUtil {
    private static ObjectMapper mapper = new ObjectMapper();

    public static String bean2Json(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
        try {
            return mapper.readValue(jsonStr, objClass);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
Copy after login

JsonLibUtil.java

public class JsonLibUtil {

    public static String bean2Json(Object obj) {
        JSONObject jsonObject = JSONObject.fromObject(obj);
        return jsonObject.toString();
    }

    @SuppressWarnings("unchecked")
    public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
        return (T) JSONObject.toBean(JSONObject.fromObject(jsonStr), objClass);
    }
}
Copy after login

准备Model类

这里我写一个简单的Person类,同时属性有Date、List、Map和自定义的类FullName,最大程度模拟真实场景。

public class Person {
    private String name;
    private FullName fullName;
    private int age;
    private Date birthday;
    private List<String> hobbies;
    private Map<String, String> clothes;
    private List<Person> friends;
    // getter/setter省略
    @Override
    public String toString() {
        StringBuilder str = new StringBuilder("Person [name=" + name + ", fullName=" + fullName + ", age="
                + age + ", birthday=" + birthday + ", hobbies=" + hobbies
                + ", clothes=" + clothes + "]
");
        if (friends != null) {
            str.append("Friends:
");
            for (Person f : friends) {
                str.append("	").append(f);
            }
        }
        return str.toString();
    }

}
Copy after login

public class FullName {
    private String firstName;
    private String middleName;
    private String lastName;

    public FullName() {
    }
    public FullName(String firstName, String middleName, String lastName) {
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;
    }
    // 省略getter和setter
    @Override
    public String toString() {
        return "[firstName=" + firstName + ", middleName="
                + middleName + ", lastName=" + lastName + "]";
    }
}
Copy after login

JSON序列化性能基准测试

@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class JsonSerializeBenchmark {
    /**
     * 序列化次数参数
     */
    @Param({"1000", "10000", "100000"})
    private int count;

    private Person p;

    public static void main(String[] args) throws Exception {
        Options opt = new OptionsBuilder()
                .include(JsonSerializeBenchmark.class.getSimpleName())
                .forks(1)
                .warmupIterations(0)
                .build();
        Collection<RunResult> results =  new Runner(opt).run();
        ResultExporter.exportResult("JSON序列化性能", results, "count", "秒");
    }

    @Benchmark
    public void JsonLib() {
        for (int i = 0; i < count; i++) {
            JsonLibUtil.bean2Json(p);
        }
    }

    @Benchmark
    public void Gson() {
        for (int i = 0; i < count; i++) {
            GsonUtil.bean2Json(p);
        }
    }

    @Benchmark
    public void FastJson() {
        for (int i = 0; i < count; i++) {
            FastJsonUtil.bean2Json(p);
        }
    }

    @Benchmark
    public void Jackson() {
        for (int i = 0; i < count; i++) {
            JacksonUtil.bean2Json(p);
        }
    }

    @Setup
    public void prepare() {
        List<Person> friends=new ArrayList<Person>();
        friends.add(createAPerson("小明",null));
        friends.add(createAPerson("Tony",null));
        friends.add(createAPerson("陈小二",null));
        p=createAPerson("邵同学",friends);
    }

    @TearDown
    public void shutdown() {
    }

    private Person createAPerson(String name,List<Person> friends) {
        Person newPerson=new Person();
        newPerson.setName(name);
        newPerson.setFullName(new FullName("zjj_first", "zjj_middle", "zjj_last"));
        newPerson.setAge(24);
        List<String> hobbies=new ArrayList<String>();
        hobbies.add("篮球");
        hobbies.add("游泳");
        hobbies.add("coding");
        newPerson.setHobbies(hobbies);
        Map<String,String> clothes=new HashMap<String, String>();
        clothes.put("coat", "Nike");
        clothes.put("trousers", "adidas");
        clothes.put("shoes", "安踏");
        newPerson.setClothes(clothes);
        newPerson.setFriends(friends);
        return newPerson;
    }
}
Copy after login

说明一下,上面的代码中

ResultExporter.exportResult("JSON序列化性能", results, "count", "秒");
Copy after login

这个是我自己编写的将性能测试报告数据填充至Echarts图,然后导出png图片的方法。

执行后的结果图:

After comparing the three, I found that this JSON library is the best to use.从上面的测试结果可以看出,序列化次数比较小的时候,Gson性能最好,当不断增加的时候到了100000,Gson明细弱于Jackson和FastJson, 这时候FastJson性能是真的牛,另外还可以看到不管数量少还是多,Jackson一直表现优异。而那个Json-lib简直就是来搞笑的。^_^

JSON反序列化性能基准测试

@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class JsonDeserializeBenchmark {
    /**
     * 反序列化次数参数
     */
    @Param({"1000", "10000", "100000"})
    private int count;

    private String jsonStr;

    public static void main(String[] args) throws Exception {
        Options opt = new OptionsBuilder()
                .include(JsonDeserializeBenchmark.class.getSimpleName())
                .forks(1)
                .warmupIterations(0)
                .build();
        Collection<RunResult> results =  new Runner(opt).run();
        ResultExporter.exportResult("JSON反序列化性能", results, "count", "秒");
    }

    @Benchmark
    public void JsonLib() {
        for (int i = 0; i < count; i++) {
            JsonLibUtil.json2Bean(jsonStr, Person.class);
        }
    }

    @Benchmark
    public void Gson() {
        for (int i = 0; i < count; i++) {
            GsonUtil.json2Bean(jsonStr, Person.class);
        }
    }

    @Benchmark
    public void FastJson() {
        for (int i = 0; i < count; i++) {
            FastJsonUtil.json2Bean(jsonStr, Person.class);
        }
    }

    @Benchmark
    public void Jackson() {
        for (int i = 0; i < count; i++) {
            JacksonUtil.json2Bean(jsonStr, Person.class);
        }
    }

    @Setup
    public void prepare() {
        jsonStr="{"name":"邵同学","fullName":{"firstName":"zjj_first","middleName":"zjj_middle","lastName":"zjj_last"},"age":24,"birthday":null,"hobbies":["篮球","游泳","coding"],"clothes":{"shoes":"安踏","trousers":"adidas","coat":"Nike"},"friends":[{"name":"小明","fullName":{"firstName":"xxx_first","middleName":"xxx_middle","lastName":"xxx_last"},"age":24,"birthday":null,"hobbies":["篮球","游泳","coding"],"clothes":{"shoes":"安踏","trousers":"adidas","coat":"Nike"},"friends":null},{"name":"Tony","fullName":{"firstName":"xxx_first","middleName":"xxx_middle","lastName":"xxx_last"},"age":24,"birthday":null,"hobbies":["篮球","游泳","coding"],"clothes":{"shoes":"安踏","trousers":"adidas","coat":"Nike"},"friends":null},{"name":"陈小二","fullName":{"firstName":"xxx_first","middleName":"xxx_middle","lastName":"xxx_last"},"age":24,"birthday":null,"hobbies":["篮球","游泳","coding"],"clothes":{"shoes":"安踏","trousers":"adidas","coat":"Nike"},"friends":null}]}";
    }

    @TearDown
    public void shutdown() {
    }
}
Copy after login

执行后的结果图:

After comparing the three, I found that this JSON library is the best to use.从上面的测试结果可以看出,反序列化的时候,Gson、Jackson和FastJson区别不大,性能都很优异,而那个Json-lib还是来继续搞笑的。

以上就是几种几种主流JSON库的基本介绍,希望能对你有所帮助!

The above is the detailed content of After comparing the three, I found that this JSON library is the best to use.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Java学习指南
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!