Conversion between Json strings and Java objects in Java

JSON (JavaScript Object Notation) is a lightweight data exchange format. Born in 2002. Easy for humans to read and write. It is also easy for machines to parse and generate. JSON is currently the mainstream front-end and back-end data transmission method.

JSON uses a completely language-independent text format, but also uses conventions similar to the C language family (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). These properties make JSON an ideal data interchange language. Almost all APPs, applications, websites, and programs are inseparable from JSON.

Common Json parsers: Gson, Fastjson, Json-lib, Jackson



1. Overview of the conversion between Json strings and Java objects in Java

1. About JSON

Json (JavaScript Object Notation) is a lightweight data exchange format. Born in 2002. Easy for humans to read and write. It is also easy for machines to parse and generate. Json is currently the mainstream front-end and back-end data transmission method.

Json adopts a completely language-independent text format, but also uses conventions similar to the C language family (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). These features make Json an ideal data exchange language. Almost all APPs, applications, websites, and programs are inseparable from Json.

2. Json parser

Common Json parsers: Gson, FastJson, Json-lib, Jackson

  • Gson (also known as Google Gson) is an open source Java library released by Google. It is characterized by fast and efficient, less code and concise;
  • FastJson is a high-performance Json processor written in Java, developed by Alibaba. No dependencies, no need for extra jars, can run directly on Jdk;
  • Json-lib is the most widely used Json parsing tool at the beginning. The disadvantage of Json-lib is that it depends on many third-party packages;
  • Compared with the Json-lib framework, Jackson relies on fewer Jar packages, is easy to use and has relatively high performance. Moreover, the Jackson community is relatively active and the update speed is relatively fast. Jackson has problems converting complex types of Json to Beans, and some collections Map and List conversions have problems.

Serialization performance: FastJson > Jackson > Gson > Jsonlib

Deserialization performance: Gson > Jackson > FastJson > Jsonlib


2. Use Gson to complete the conversion between Json strings and Java objects

1. Introduction to Gson

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

The application of Gson mainly consists of two conversion functions, toJson and fromJson. It has no dependencies and does not require additional jars. It can run directly on Jdk. Before using this object conversion, you need to create the object type and its members to 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, which is an artifact of Json parsing.

Ps: Although Gson is impeccable in function, it has a gap in performance compared to FastJson.

2. Gson introduction

Maven dependency import:

 <!--gson-->
 <dependency>
     <groupId>com.google.code.gson</groupId>
     <artifactId>gson</artifactId>
     <version>2.10.1</version>
 </dependency>

3. Gson main class introduction

Gson main class:

  • Gson class: the most basic tool class for parsing Json
  • JsonParser class: Parser to parse the parse tree from Json to JsonElements
  • JsonElement class: a class representing a Json element
  • JsonObject class: Json object type
  • JsonArray class: JsonObject array
  • TypeToken class: used to create type, such as generic List<?>

4、Gson Demo

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonTestClass {
    
    

    public static void main(String[] args) {
    
    
        User user = new User();
        user.setId(1);
        user.setName("栗筝i");
        Gson g = new GsonBuilder().create();
        String str = g.toJson(user);
        System.out.println(str);
    }
}

Ps: By default, the key corresponding to the null value is not serialized. If you want to serialize the key corresponding to the null value, you only need to change the above creation code to the following code:

Gson g = new GsonBuilder().serializeNulls().create();

5. Interchange between objects and Json

# bean conversion Json

Gson gson = new Gson();
// obj 是对象
String json = gson.toJson(obj);

Ps: When we need to isolate the member variable attribute name of the defined class from the format name in the returned Json, we can use the @SerializedName annotation mark! !

# Json conversion bean

Gson gson = new Gson();
String json = "{\"id\":\"1\",\"name\":\"栗筝i\"}";
Book book = gson.fromJson(json, Book.class);

# Json converts complex beans, such as List, Set

Gson gson = new Gson();
String json = "[{\"id\":\"1\",\"name\":\"栗筝i\"},{\"id\":\"2\",\"name\":\"栗筝ii\"}]";
// 将 Json 转换成 List
List list = gson.fromJson(json, new TypeToken<LIST>() {
    
    }.getType());
// 将 Json 转换成 Set
Set set = gson.fromJson(json, new TypeToken<SET>() {
    
    }.getType());

6. Directly operate Json and some Json tools

# Format JSON:

String json = "[{\"id\":\"1\",\"name\":\"栗筝i\"},{\"id\":\"2\",\"name\":\"栗筝ii\"}]";
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(json);
json = gson.toJson(je);

# Determine whether the string is Json (judging whether it is Json by capturing the exception)

String json = "[{\"id\":\"1\",\"name\":\"栗筝i\"},{\"id\":\"2\",\"name\":\"栗筝ii\"}]";
boolean jsonFlag;
try {
    
    
     new JsonParser().parse(str).getAsJsonObject();
     jsonFlag = true;
} catch (Exception e) {
    
    
     jsonFlag = false;
}

# Get properties from Json string

String json = "{\"id\":\"1\",\"name\":\"栗筝i\"}";
String propertyName = 'id';
String propertyValue = "";
try {
    
    
    JsonParser jsonParser = new JsonParser();
    JsonElement element = jsonParser.parse(json);
    JsonObject jsonObj = element.getAsJsonObject();
    propertyValue = jsonObj.get(propertyName).toString();
} catch (Exception e) {
    
    
    propertyValue = null;
}

# Remove an attribute in Json

String json = "{\"id\":\"1\",\"name\":\"栗筝i\"}";
String propertyName = 'id';
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
JsonObject jsonObj = element.getAsJsonObject();
jsonObj.remove(propertyName);
json = jsonObj.toString();

# Add attributes to Json

String json = "{\"id\":\"1\",\"name\":\"栗筝i\"}";
String propertyName = 'age';
Object propertyValue = "26";
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
JsonObject jsonObj = element.getAsJsonObject();
jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue));
json = jsonObj.toString();

# Modify the properties in Json

String json = "{\"id\":\"1\",\"name\":\"栗筝i\"}";
String propertyName = 'name';
Object propertyValue = "栗筝ii";
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
JsonObject jsonObj = element.getAsJsonObject();
jsonObj.remove(propertyName);
jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue));
json = jsonObj.toString();

# Determine whether there is an attribute in Json

String json = "{\"id\":\"1\",\"name\":\"栗筝i\"}";
String propertyName = 'name';
boolean isContains = false ;
JsonParser jsonParser = new JsonParser();
JsonElement element = jsonParser.parse(json);
JsonObject jsonObj = element.getAsJsonObject();
isContains = jsonObj.has(propertyName);

7. gsonUtil tool class

import com.dechnic.common.anno.gson.Exclude;
import com.dechnic.common.po.ObjectTypeAdapter;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GsonUtll {
    
    
    private static Gson gson;
    static {
    
    
        ExclusionStrategy strategy = new ExclusionStrategy() {
    
    
            @Override
            public boolean shouldSkipField(FieldAttributes f) {
    
    
                return f.getAnnotation(Exclude.class) !=null;
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
    
    
                return false;
            }
        };
        gson = new GsonBuilder().disableHtmlEscaping().setExclusionStrategies(strategy).registerTypeAdapter(new TypeToken<Map<String,Object>>(){
    
    }.getType(),new ObjectTypeAdapter()).serializeNulls().create();
    }
  
    public static Map<String,Object> jsonStr2Map(String jsonStr){
    
    
        return gson.fromJson(jsonStr, new TypeToken<Map<String, Object>>() {
    
    
        }.getType());
    }
  
    public static List<Map<String,Object>> jsonStr2ListMap(String jsonStr){
    
    
        return gson.fromJson(jsonStr, new TypeToken<List<Map<String, Object>>>() {
    
    
        }.getType());
    }
  
    public static String toJSON(Object object){
    
    
        return gson.toJson(object);
    }
  
    public static <T> List<T> json2ListBean(String result, Class<T> t){
    
    
        List list = gson.fromJson(result, new TypeToken<List>() {
    
    
        }.getType());
        List list2 = new ArrayList();
        for (Object o : list) {
    
    
            list2.add(json2Bean(toJSON(o),t));
        }
        return list2;
    }
  
    public static <T> T json2Bean(String result,Class<T>t){
    
    
        return gson.fromJson(result, t);
    }

}

3. Use FastJson to complete the conversion between Json strings and Java objects

1. Introduction to FastJson

Fastjson, developed by Alibaba, is a high-performance Json processor written in Java language. No dependencies, no need for extra Jar exceptions, and can run directly on Jdk.

FastJson will have some problems in converting Json of complex types of beans. There may be reference types, which will cause errors in Json conversion, and references need to be formulated.

FastJson uses an original algorithm to maximize the speed of parse, surpassing all Json libraries.

2. Introduction of FastJson

Maven dependency import:

<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.23</version>
</dependency>

3. The null value corresponds to the serialization of the key

When FastJson converts a Java object to Json, it does not serialize the key corresponding to the null value by default. That is to say, when the properties in the object are empty, when converting to Json, those properties with null values ​​​​are not serialized

Take a closer look at the input parameters of FastJson's method of converting Java objects to Json:

public static String toJSONString(Object object, com.alibaba.fastjson2.JSONWriter.Feature... features)

You can see that features is an array JSONWriter.Feature is its serialization property:

  • QuoteFieldNames————Whether to use double quotes when outputting the key, the default is true
  • WriteMapNullValue———whether to output a field whose value is null, the default is false
  • WriteNullNumberAsZero————If the value field is null, the output is 0 instead of null
  • WriteNullListAsEmpty————If the List field is null, the output will be [] instead of null
  • WriteNullStringAsEmpty————If the character type field is null, the output will be "" instead of null
  • WriteNullBooleanAsFalse—————If the Boolean field is null, the output is false instead of null

4, FastJson Demo

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;

public class FastJsonTestClass {
    
    

    public static void main(String[] args) {
    
    
        User user = new User();
        user.setIdd(1);
        user.setName("栗筝i");
        String str = JSONObject.toJSONString(user, JSONWriter.Feature.WriteMapNullValue);
        System.out.println(str);

    }
}

Ps: When we need to isolate the member variable attribute name of the defined class from the format name in the returned Json, we can use the @JSONField annotation mark! !

5. Interchange between objects and Json

# Object to Json

User user = new User();
user.setId(1);
user.setName("栗筝i");
System.out.println(JSON.toJSONString(user, JSONWriter.Feature.UseSingleQuotes));

# Json to object

String json = "{\"id\":1,'name':'张三'}";
User userModel = JSON.parseObject(json, User.class);

# Parse Json to JSONObject

String json = "{\"id\":1,'name':'张三'}";
JSONObject data = JSON.parseObject(json);
System.out.println(data.get("id"));

# Parse Json to JSONArray

String text = "...";
JSONArray data = JSON.parseArray(text);

Guess you like

Origin blog.csdn.net/weixin_45187434/article/details/129010869