Common json analytic method java, library and performance comparison

Common json parsing has native JSONObject and JSONArray method, Google's GSON library, Ali fastjson, there jackson, json-lib.

  • Gson (Project address: https: //github.com/google/gson). Gson is the most versatile Json parsing artifact, Gson Initially, it was to cope with domestic demand while Google's own R & D evolved from Google, but since publicly released the first edition in May 2008 the company has been a lot of users or applications. Gson application mainly fromJson toJson with two conversion functions, no dependency, no additional JAR exceptions, can be run directly on the JDK. But before using this type of object conversion you must first create a good object and its members will be successful successfully converted into the corresponding JSON string object. As long as the class which get and set methods, can Gson complex type or bean to bean to json json conversion is JSON parsing artifact.
  • FastJson (Project address: https: //github.com/alibaba/fastjson). Fastjson Java language is written in a high-performance JSON processor, developed by Alibaba. No dependence, no additional jar exception, can be directly run on JDK. FastJson will appear on a complex type of Bean convert Json some of the problems, the type of reference may occur, resulting Json conversion error, the need for reference. FastJson using original algorithm, will parse the speed to the extreme, more than all the json library.
  • Jackson (Project address: https: //github.com/FasterXML/jackson). Compared json-lib frame, Jackson jar package depends less easy to use and the performance should be relatively higher. And Jackson community is relatively active, the speed is faster. Jackson bean cause problems for complex json type of conversion, a collection of Map, List of the conversion problems. Jackson For complex types of bean convert Json, Json format conversion json format instead of the standard.
  • Json-lib (Project Address: http: //json-lib.sourceforge.net/index.html). json-lib beginning is the most widely used analytical tool json, json-lib a bad place really is dependent on many third-party packages, including commons-beanutils.jar, commons-collections-3.2.jar, commons-lang- 2.6.jar, commons-logging-1.1.1.jar, ezmorph-1.0.6.jar, for the conversion of complex types, json-lib converted to json bean there defects, such as occur inside a class of another class list or map set, json-lib problem arises from bean to json conversion. json-lib in function and performance of the above can not meet the needs of the Internet now.

    1, java analytically

  • JSONObject parse json objects
  • Analytical json array JSONArray
    e.g. json string:
{
    "personData": [
        {
            "age": 12,
            "name": "nate",
            "schoolInfo": [
                {
                    "School_name": "清华"
                },
                {
                    "School_name": "北大"
                }
            ],
            "url": "http://pic.yesky.com/uploadImages/2014/345/36/E8C039MU0180.jpg"
        },
        {
            "age": 24,
            "name": "jack",
            ···
        }
    ],
    "result": 1
}

Json analysis of this data,

  • The first layer is a brace brackets, i.e. jsonObect the object, and the object which has a personData JSONArray array, and a result attribute
  • A second layer of personData JSONArray array, which in addition to its properties, there is a schoolInfo array of JSONArray
  • The third time was schoolInfo JSONArray array of objects inside JSONObject

Resolution:

public class Httpjson extends Thread {
    private String url;
    private Context context;
    private ListView listView;
    private JsonAdapter adapter;
    private Handler handler;

    public Httpjson(String url, ListView listView, JsonAdapter adapter, Handler handler) {
        super();
        this.url = url;
        this.listView = listView;
        this.adapter = adapter;
        this.handler = handler;
    }

    @Override
    public void run() {
        URL httpUrl;
        try {
            httpUrl = new URL(url);
            ···
    }

    /**
     * 从网络中获取JSON字符串,然后解析
     * @param json
     * @return
     */
    private List<Person> jsonParse(String json) {
        try {
            List<Person> personlist = new ArrayList<Person>();
            JSONObject jsonObject = new JSONObject(json);
            int result = jsonObject.getInt("result");
            if (result == 1) {
                JSONArray jsonArray = jsonObject.getJSONArray("personData");
                for (int i = 0; i < jsonArray.length(); i++) {
                    Person person = new Person();
                    JSONObject personData = jsonArray.getJSONObject(i);
                    int age = personData.getInt("age");
                    String url = personData.getString("url");
                    String name = personData.getString("name");
                    ···    
                    JSONArray schoolInfoArray = personData.getJSONArray("schoolInfo");
                    for (int j = 0; j < schoolInfoArray.length(); j++) {
                        JSONObject schoolInfojson = schoolInfoArray.getJSONObject(j);
                        String schoolName = schoolInfojson.getString("School_name");
                        ···
                    }
                    ···
                }
                return personlist;
            } else {
                Toast.makeText(context, "erro", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("JsonParseActivity", "json解析出现了问题");
        }

        return null;
    }
}

2, gson resolve

(1 Introduction

  GSON is provided by Google for mapping between Java objects and JSON data Java class libraries. Json a character can be transformed into a Java object, or into a Java Json string.

(2) features

  • Fast, efficient
  • Less code, concise
  • Object-Oriented
  • Analytical data transfer and convenience

(3) the preparation of bean class

To write the bean class gson make use of, which is the key names, such as date, safe these must correspond together. The second is in the bean class encountered braces to write a class class, experience square brackets write a Arraylist array. These are the main rules! Class class written in the form of internal within the interior.

public class GsonParseMoGuBean {
    
    public String data;    
    public String name;
    public String packageName;
    ···
    
    public ArrayList<SafeInfo> safe;
    
    public class SafeInfo {
        public String safeDes;
        ···                
    }
    
    public ArrayList<String> screen;
    
}

(4) The format string json parsed into java object {}

Java对象

/**
     * //将json格式的字符窜{}转换为java对象
     */
    private void jsonToJavaObjectByGson() {
        
        //1获取或创建json数据
        String json ="{\n" +
        "\t\"id\":2, \"name\":\"大虾\", \n" + 
        "\t\"price\":12.3, \n" +
        "\t\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"\n" + 
        "}\n";
        
        //2解析json数据
        Gson gson =new Gson();
        
        //第一个参数是要解析的数据,第二个参数是解析生成的java对象的类
        ShopInfo shopInfo =  gson.fromJson(json, ShopInfo.class);
        
    }

(5)} {json format string is parsed into java object list

private void jsonToJavaListByGson() {
        
        //1获取或创建json数据
         String json = "[\n" + 
        "    {\n" + 
                 "        \"id\": 1,\n" + 
        "        \"imagePath\": \"http://192.168.10.165:8080/f1.jpg\",\n" + 
                 "        \"name\": \"大虾 1\",\n" + 
        "        \"price\": 12.3\n" +             "    },\n" +             "    {\n" +  
                 "        \"id\": 2,\n" + 
        "        \"imagePath\": \"http://192.168.10.165:8080/f2.jpg\",\n" +
        "        \"name\": \"大虾 2\",\n" + 
        "        \"price\": 12.5\n" +             "    }\n" +
        "]";
         
        
        //2解析json数据
         Gson gson =new Gson();      
         
         //List<ShopInfo>:是要返回数据的集合
         List<ShopInfo> shops = gson.fromJson(json,new TypeToken<List<ShopInfo>>(){}.getType());
         
        
        //3显示数据
         tv_gson_orignal.setText(json);
            
        tv_gson_last.setText(shops.toString());
        
    }

(6) to convert a java object string json

private void javaToJSONByGson() {
        
        //1获取或创建java数据
        ShopInfo shopInfo = new ShopInfo(1,"鲍鱼",250.0,"baoyu");
        
        
        //2生成json数据
        Gson gson = new Gson();
        
        String json = gson.toJson(shopInfo);
        
        //3显示数据
         tv_gson_orignal.setText(shopInfo.toString());
            
            tv_gson_last.setText(json);
        
    }

(7) is converted into an object list java json string []

/**
     * //将java对象的list转换为json字符窜
     */
    private void javaToJSONArrayByGson() {
        
        //1获取或创建java数据
        List<ShopInfo> shops =new ArrayList<ShopInfo>();
        
        ShopInfo baoyu = new ShopInfo(1,"鲍鱼",250.0,"baoyu");
        
        ShopInfo longxia = new ShopInfo(1,"龙虾",250.0,"longxia");
        
        shops.add(baoyu);
        
        shops.add(longxia);
        
        //2生成json数据
        Gson gson = new Gson();
        
        String json = gson.toJson(shops);
        
        
        //3显示数据
         tv_gson_orignal.setText(shops.toString());
            
            tv_gson_last.setText(json);
    }

3, fastjson

(1 Introduction

  In everyday java project development, JSON is used more and more frequently, for Json processing tools there are many. Then you tell us about Ali open source JSON framework FastJson a high-performance, fully functional, full support for standard JSON library, now increasingly favored by developers.

(2) features

  Fastjson is a well-written in the Java language features high performance JSON library. It uses a "rapid and orderly assumed to match" algorithm, the JSONParse performance to the extreme, is the fastest JSON Java language library.

(4) {} string json format into Java objects

private void jsonToJavaObjectByFastJson() {

// 1 获取或创建 JSON 数据
 String json = "{\n" +
"\t\"id\":2, \"name\":\"大虾\", \n" +
"\t\"price\":12.3, \n" +
"\t\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\ "\n" +
"}\n";

// 2 解析 JSON 数据
ShopInfo shopInfo = JSON.parseObject(json, ShopInfo.class);

}

(4) The format string json [] to Java objects List

private void jsonToJavaListByFastJson() {

// 1 获取或创建 JSON 数据
 String json = "[\n" +
" {\n"+
" \"id\": 1,\n" +
" \"imagePath\":
\"http://192.168.10.165:8080/f1.jpg\",\n" +
" " " " " "
\"name\": \"大虾 1\",\n" +
\"price\": 12.3\n" + },\n" +
{\n"+
\"id\": 2,\n" + \"imagePath\":
\"http://192.168.10.165:8080/f2.jpg\",\n" +
" \"name\": \"大虾 2\",\n" +
" \"price\": 12.5\n" + " }\n"+
"]";

// 2 解析 JSON 数据
List<ShopInfo> shopInfos = JSON.parseArray(json, ShopInfo.class);
}

(5) converts Java objects json string

private void javaToJsonObjectByFastJson() {
// 1 获取 Java 对象
ShopInfo shopInfo = new ShopInfo(1, "鲍鱼", 250.0, "baoyu");
// 2 生成 JSON 数据
String json = JSON.toJSONString(shopInfo);
// 3 数据显示 tv_fastjson_orignal.setText(shopInfo.toString()); tv_fastjson_last.setText(json);
}

(7) converting the object to json List Java String []

private void javaToJsonArrayByFastJson() {
// 1 获取 Java 集合
List<ShopInfo> shops = new ArrayList<>();
ShopInfo baoyu = new ShopInfo(1, "鲍鱼", 250.0, "baoyu");
ShopInfo longxia = new ShopInfo(2, "龙虾", 251.0, "longxia"); shops.add(baoyu);
shops.add(longxia);
// 2 生成 JSON 数据
String json = JSON.toJSONString(shops);
// 3 数据显示 tv_fastjson_orignal.setText(shops.toString()); tv_fastjson_last.setText(json);
}

4, performance comparison

Select an appropriate JSON library from multiple aspects to consider:

  • String to parse performance JSON
  • String to parse performance JavaBean
  • JSON structure JavaBean properties
  • JSON construct the set of performance
  • Ease of
    writing performance test
    next start writing these four performance test code library.

(1) adding dependency maven

The first is of course dependent on four add maven repository, in fairness, I use them all the latest version:

<!-- 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>

(2) four library tools

java 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);
}
}

java 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);
    }
}

java 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;
    }
}
}

java 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);
    }
}

(3) Preparation Model class

Here I wrote a simple Person class, while the class attributes FullName Date, List, Map and custom maximum extent simulate real-world scenarios.

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 + "]\n");
        if (friends != null) {
            str.append("Friends:\n");
            for (Person f : friends) {
                str.append("\t").append(f);
            }
        }
        return str.toString();
    }

}
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 + "]";
    }
}

(4) JSON serialization benchmark

@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;
    }
}

Explain the above code

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

This is the way I have written to fill Echarts map, then export the png image of the performance test report data, I will not put up specific code, refer to my github source.

After the results of the implementation chart:

As can be seen from the above test results, the number of sequences is small when, Gson best performance, when increasing the time to 100000, Gson weaker than Jackson and FASTJSON details, this property is true when FASTJSON cattle, may also regardless of the number or see fewer and more, Jackson has been outstanding performance. And that is simply to Json-lib funny. ^ _ ^

(5) JSON deserialization performance benchmark

@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() {
    }
}

After the results of the implementation chart:

As can be seen from the above test results, deserialization time, Gson, Jackson and FastJson not very different, very good performance, and that Json-lib or to continue funny.

Reprinted statement: Performance Comparison in part by the customer can create a bear © flying dirt Bear blog.

Guess you like

Origin www.cnblogs.com/zyh0430/p/12009310.html