Mutual conversion between Java entities and JSON

Mutual conversion between Java entities and JSON

1. First write a Java entity for testing

code show as below:

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.Data;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 测试用户类
 *
 * @author:gan
 * @date: 2023-04-28 15:33
 */
@Data
public class User {
    
    
    private String name;

    private Integer age;

    private Date birthday;

    private char sex;

    private Float height;

    private Double weight;

    private BigDecimal money;

    private Boolean adult;

	//下面这些初始化为空,用于后面测试效果时用

    private String nameDesc;

    private Integer ageDesc;

    private Date birthdayDesc;

    private char sexDesc;

    private Float heightDesc;

    private Double weightDesc;

    private BigDecimal moneyDesc;

    private Boolean adultDesc;

    public User() {
    
    
    }

    public User(String name, Integer age, Date birthday, char sex, Float height, Double weight, BigDecimal money, Boolean adult) {
    
    
        this.name = name;
        this.age = age;
        this.birthday = birthday;
        this.sex = sex;
        this.height = height;
        this.weight = weight;
        this.money = money;
        this.adult = adult;
    }
}

Initialize and output:

public static void main(String[] args) {
    
    
        User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
        System.out.println("toString方法:" + user);
    }

insert image description here
Note that if the "@Data" annotation is not used, the get and set methods must be added, otherwise the converted Json will be empty!

2. Convert Java entities to Json

1. Based on com.alibaba.fastjson.JSON

Mainly the use of the SerializerFeature enumeration class, you can see this blog for details:

https://blog.csdn.net/xiang__liu/article/details/81570923

Or look here:

https://www.javadoc.io/static/com.alibaba/fastjson/1.2.2/com/alibaba/fastjson/serializer/SerializerFeature.html#BeanToArray

The following is a demonstration of the use of SerializerFeature:

(1), JSON.toJSONString(user), will discard fields with empty values.

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

System.out.println("=================================JSON.toJSONString start================================");

String jsonStr1 = JSON.toJSONString(user);
System.out.println("jsonStr1:" + jsonStr1);

The result of the operation is as follows:

insert image description here
It can be seen that directly using toJSONString to convert a Java entity to Json will discard the fields that are not explicitly initialized.

"\u0000" is the default value of char type, relative to null.

(2), JSON.toJSONString(user, SerializerFeature.WriteMapNullValue), retain the field whose value is empty, and initialize it to null.

Adding "SerializerFeature.WriteMapNullValue" will output fields with null values.

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

System.out.println("=================================JSON.toJSONString start================================");

String jsonStr1 = JSON.toJSONString(user);
System.out.println("jsonStr1:" + jsonStr1);

String jsonStr2 = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue);
System.out.println("jsonStr2:" + jsonStr2);

The result of the operation is as follows:

insert image description here

(3), JSON.toJSONString(user, SerializerFeature.WriteNonStringValueAsString), will add "" to the non-empty field value, and discard the uninitialized field.

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

System.out.println("=================================JSON.toJSONString start================================");

String jsonStr1 = JSON.toJSONString(user);
System.out.println("jsonStr1:" + jsonStr1);

String jsonStr2 = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue);
System.out.println("jsonStr2:" + jsonStr2);

String jsonStr3 = JSON.toJSONString(user, SerializerFeature.WriteNonStringValueAsString);
System.out.println("jsonStr3:" + jsonStr3);

The result of the operation is as follows:

insert image description here

(4), JSON.toJSONString(user, SerializerFeature.WriteNullStringAsEmpty), will add "" to the field of String type, keep the String type parameter that is not displayed and initialize it, keep the field initialized to null by default, and discard other uninitialized, Fields of non-String type.

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

System.out.println("=================================JSON.toJSONString start================================");

String jsonStr1 = JSON.toJSONString(user);
System.out.println("jsonStr1:" + jsonStr1);

String jsonStr2 = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue);
System.out.println("jsonStr2:" + jsonStr2);

String jsonStr3 = JSON.toJSONString(user, SerializerFeature.WriteNonStringValueAsString);
System.out.println("jsonStr3:" + jsonStr3);

String jsonStr4 = JSON.toJSONString(user, SerializerFeature.WriteNullStringAsEmpty);
System.out.println("jsonStr4:" + jsonStr4);

The result of the operation is as follows:

insert image description here

(5), JSON.toJSONString(user, SerializerFeature.WriteNullListAsEmpty), will add "" to non-empty, String-type fields, keep the fields initialized to null by default, and discard other uninitialized, non-String-type fields.

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

System.out.println("=================================JSON.toJSONString start================================");

String jsonStr1 = JSON.toJSONString(user);
System.out.println("jsonStr1:" + jsonStr1);

String jsonStr2 = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue);
System.out.println("jsonStr2:" + jsonStr2);

String jsonStr3 = JSON.toJSONString(user, SerializerFeature.WriteNonStringValueAsString);
System.out.println("jsonStr3:" + jsonStr3);

String jsonStr4 = JSON.toJSONString(user, SerializerFeature.WriteNullStringAsEmpty);
System.out.println("jsonStr4:" + jsonStr4);

String jsonStr5 = JSON.toJSONString(user, SerializerFeature.WriteNullListAsEmpty);
System.out.println("jsonStr5:" + jsonStr5);

The result of the operation is as follows:
insert image description here

(6), JSON.toJSONString(user, SerializerFeature.QuoteFieldNames), the converted field name will be added with "", which is the same as the default.

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

System.out.println("=================================JSON.toJSONString start================================");

String jsonStr1 = JSON.toJSONString(user);
System.out.println("jsonStr1:" + jsonStr1);

String jsonStr2 = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue);
System.out.println("jsonStr2:" + jsonStr2);

String jsonStr3 = JSON.toJSONString(user, SerializerFeature.WriteNonStringValueAsString);
System.out.println("jsonStr3:" + jsonStr3);

String jsonStr4 = JSON.toJSONString(user, SerializerFeature.WriteNullStringAsEmpty);
System.out.println("jsonStr4:" + jsonStr4);

String jsonStr5 = JSON.toJSONString(user, SerializerFeature.WriteNullListAsEmpty);
System.out.println("jsonStr5:" + jsonStr5);

String jsonStr6 = JSON.toJSONString(user, SerializerFeature.QuoteFieldNames);
System.out.println("jsonStr6:" + jsonStr6);

The result of the operation is as follows:

insert image description here

(7), JSON.toJSONString(user, SerializerFeature.WriteDateUseDateFormat), the Date type is the input format after conversion, and the default is timestamp.

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

System.out.println("=================================JSON.toJSONString start================================");

String jsonStr1 = JSON.toJSONString(user);
System.out.println("jsonStr1:" + jsonStr1);

String jsonStr2 = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue);
System.out.println("jsonStr2:" + jsonStr2);

String jsonStr3 = JSON.toJSONString(user, SerializerFeature.WriteNonStringValueAsString);
System.out.println("jsonStr3:" + jsonStr3);

String jsonStr4 = JSON.toJSONString(user, SerializerFeature.WriteNullStringAsEmpty);
System.out.println("jsonStr4:" + jsonStr4);

String jsonStr5 = JSON.toJSONString(user, SerializerFeature.WriteNullListAsEmpty);
System.out.println("jsonStr5:" + jsonStr5);

String jsonStr6 = JSON.toJSONString(user, SerializerFeature.QuoteFieldNames);
System.out.println("jsonStr6:" + jsonStr6);

String jsonStr7 = JSON.toJSONString(user, SerializerFeature.WriteDateUseDateFormat);
System.out.println("jsonStr7:" + jsonStr7);

The result of the operation is as follows:

insert image description here

(8), JSON.toJSONString(user, SerializerFeature.WriteNullNumberAsZero), after the conversion, the uninitialized number type (BigDecimal, Float, Double) fields will be initialized to 0, the fields initialized to null will be kept, and other types that are not initialized will be discarded field.

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

System.out.println("=================================JSON.toJSONString start================================");

String jsonStr1 = JSON.toJSONString(user);
System.out.println("jsonStr1:" + jsonStr1);

String jsonStr2 = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue);
System.out.println("jsonStr2:" + jsonStr2);

String jsonStr3 = JSON.toJSONString(user, SerializerFeature.WriteNonStringValueAsString);
System.out.println("jsonStr3:" + jsonStr3);

String jsonStr4 = JSON.toJSONString(user, SerializerFeature.WriteNullStringAsEmpty);
System.out.println("jsonStr4:" + jsonStr4);

String jsonStr5 = JSON.toJSONString(user, SerializerFeature.WriteNullListAsEmpty);
System.out.println("jsonStr5:" + jsonStr5);

String jsonStr6 = JSON.toJSONString(user, SerializerFeature.QuoteFieldNames);
System.out.println("jsonStr6:" + jsonStr6);

String jsonStr7 = JSON.toJSONString(user, SerializerFeature.WriteDateUseDateFormat);
System.out.println("jsonStr7:" + jsonStr7);

String jsonStr8 = JSON.toJSONString(user, SerializerFeature.WriteNullNumberAsZero);
System.out.println("jsonStr8:" + jsonStr8);

The result of the operation is as follows:

insert image description here

(9), JSON.toJSONString(user, SerializerFeature.WriteNullBooleanAsFalse), after conversion, initialize the uninitialized Boolean type fields to false, keep the fields initialized to null, and discard other types of uninitialized fields.

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

System.out.println("=================================JSON.toJSONString start================================");

String jsonStr1 = JSON.toJSONString(user);
System.out.println("jsonStr1:" + jsonStr1);

String jsonStr2 = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue);
System.out.println("jsonStr2:" + jsonStr2);

String jsonStr3 = JSON.toJSONString(user, SerializerFeature.WriteNonStringValueAsString);
System.out.println("jsonStr3:" + jsonStr3);

String jsonStr4 = JSON.toJSONString(user, SerializerFeature.WriteNullStringAsEmpty);
System.out.println("jsonStr4:" + jsonStr4);

String jsonStr5 = JSON.toJSONString(user, SerializerFeature.WriteNullListAsEmpty);
System.out.println("jsonStr5:" + jsonStr5);

String jsonStr6 = JSON.toJSONString(user, SerializerFeature.QuoteFieldNames);
System.out.println("jsonStr6:" + jsonStr6);

String jsonStr7 = JSON.toJSONString(user, SerializerFeature.WriteDateUseDateFormat);
System.out.println("jsonStr7:" + jsonStr7);

String jsonStr8 = JSON.toJSONString(user, SerializerFeature.WriteNullNumberAsZero);
System.out.println("jsonStr8:" + jsonStr8);

String jsonStr9 = JSON.toJSONString(user, SerializerFeature.WriteNullBooleanAsFalse);
System.out.println("jsonStr9:" + jsonStr9);

The result of the operation is as follows:

insert image description here

(10), JSON.toJSONString(user, SerializerFeature.PrettyFormat), format Json, and discard other uninitialized fields.

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

System.out.println("=================================JSON.toJSONString start================================");

String jsonStr1 = JSON.toJSONString(user);
System.out.println("jsonStr1:" + jsonStr1);

String jsonStr2 = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue);
System.out.println("jsonStr2:" + jsonStr2);

String jsonStr3 = JSON.toJSONString(user, SerializerFeature.WriteNonStringValueAsString);
System.out.println("jsonStr3:" + jsonStr3);

String jsonStr4 = JSON.toJSONString(user, SerializerFeature.WriteNullStringAsEmpty);
System.out.println("jsonStr4:" + jsonStr4);

String jsonStr5 = JSON.toJSONString(user, SerializerFeature.WriteNullListAsEmpty);
System.out.println("jsonStr5:" + jsonStr5);

String jsonStr6 = JSON.toJSONString(user, SerializerFeature.QuoteFieldNames);
System.out.println("jsonStr6:" + jsonStr6);

String jsonStr7 = JSON.toJSONString(user, SerializerFeature.WriteDateUseDateFormat);
System.out.println("jsonStr7:" + jsonStr7);

String jsonStr8 = JSON.toJSONString(user, SerializerFeature.WriteNullNumberAsZero);
System.out.println("jsonStr8:" + jsonStr8);

String jsonStr9 = JSON.toJSONString(user, SerializerFeature.WriteNullBooleanAsFalse);
System.out.println("jsonStr9:" + jsonStr9);

String jsonStr10 = JSON.toJSONString(user, SerializerFeature.PrettyFormat);
System.out.println("jsonStr10:" + jsonStr10);

The result of the operation is as follows:

insert image description here

2. Based on com.alibaba.fastjson.JSONObject

JSONObject is a subclass of JSON and does not override the "toJSONString" method, so the effect is the same.
insert image description here

code show as below:

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

System.out.println("=================================JSONObject.toJSONString start================================");

String jsonObjectStr1 = JSONObject.toJSONString(user);
System.out.println("jsonObjectStr1:" + jsonObjectStr1);

String jsonObjectStr2 = JSONObject.toJSONString(user, SerializerFeature.WriteMapNullValue);
System.out.println("jsonObjectStr2:" + jsonObjectStr2);

String jsonObjectStr3 = JSONObject.toJSONString(user, SerializerFeature.WriteNonStringValueAsString);
System.out.println("jsonObjectStr3:" + jsonObjectStr3);

String jsonObjectStr4 = JSONObject.toJSONString(user, SerializerFeature.WriteNullStringAsEmpty);
System.out.println("jsonObjectStr4:" + jsonObjectStr4);

String jsonObjectStr5 = JSONObject.toJSONString(user, SerializerFeature.WriteNullListAsEmpty);
System.out.println("jsonObjectStr5:" + jsonObjectStr5);

String jsonObjectStr6 = JSONObject.toJSONString(user, SerializerFeature.QuoteFieldNames);
System.out.println("jsonObjectStr6:" + jsonObjectStr6);

String jsonObjectStr7 = JSONObject.toJSONString(user, SerializerFeature.WriteDateUseDateFormat);
System.out.println("jsonObjectStr7:" + jsonObjectStr7);

String jsonObjectStr8 = JSONObject.toJSONString(user, SerializerFeature.WriteNullNumberAsZero);
System.out.println("jsonObjectStr8:" + jsonObjectStr8);

String jsonObjectStr9 = JSONObject.toJSONString(user, SerializerFeature.WriteNullBooleanAsFalse);
System.out.println("jsonObjectStr9:" + jsonObjectStr9);

String jsonObjectStr10 = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat);
System.out.println("jsonObjectStr10:" + jsonObjectStr10);

System.out.println("=================================JSONObject.toJSONString end================================");

insert image description here

3. Based on the writeValueAsString method of com.fasterxml.jackson.databind.ObjectMapper

code show as below:

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

ObjectMapper objectMapper = new ObjectMapper();
try {
    
    
    String objectMapperStr = objectMapper.writeValueAsString(user);
    System.out.println("objectMapperStr:" + objectMapperStr);
} catch (JsonProcessingException e) {
    
    
    e.printStackTrace();
}

The result of the operation is as follows:

insert image description here
The writeValueAsString method will retain the fields that are not displayed and initialized, except for the initial value of char type "\u0000", all others are "null".

4. Based on the toJson method of com.google.gson.Gson.

(1) Instantiate a Gson directly, and pass the Java entity to toJson in the instance, and the uninitialized fields will be discarded.

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

Gson gson = new Gson();

String gsonStr1 = gson.toJson(user);
System.out.println("gsonStr1:" + gsonStr1);

The result of the operation is as follows:

insert image description here
The char type is still preserved.

(2) While converting to json, retain the fields that have not been initialized.

"Gson gson = new Gson();" can simply convert Java entities to json. To keep fields that are not explicitly initialized, you need to use "GsonBuilder" to initialize "Gson". The code is as follows:

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

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

String gsonStr1 = gson.toJson(user);
System.out.println("gsonStr1:" + gsonStr1);

The result of the operation is as follows:

insert image description here
It can be seen that the fields that are not displayed for initialization are reserved, and the values ​​​​are all "null".

(3). Set the time format.

You can see above that the time format defaults to the internationalized format. What should I do if I want to convert it to "yyyy, MM, dd, hour:minute:second"? You can use "setDateFormat" to format the time, the code is as follows:

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

Gson gson = new GsonBuilder()
    .serializeNulls()
    .setDateFormat("yyyy年MM月dd日 HH:mm:ss")
    .create();

String gsonStr1 = gson.toJson(user);
System.out.println("gsonStr1:" + gsonStr1);

The result of the operation is as follows:

insert image description here
You can see that the time has been converted to the target format.

(4), formatted output.

If you feel that only one line of the converted json is ugly, you can use "setPrettyPrinting" to format the json format, the code is as follows:

User user = new User("王宇", 25, DateUtil.parse("1998-10-12 13:25:22"), '男', 180.0f, 71.55, new BigDecimal("2104.5"), true);
System.out.println("toString方法:" + user);

Gson gson = new GsonBuilder()
    .serializeNulls()
    .setDateFormat("yyyy年MM月dd日 HH:mm:ss")
    .setPrettyPrinting()
    .create();

String gsonStr1 = gson.toJson(user);
System.out.println("gsonStr1:" + gsonStr1);

The result of the operation is as follows:

insert image description here

3. Convert Json to Java entity

1. First get the test Json

Get the Java entity for testing and convert it into Json, formatted as follows:

{
    
    
	"adult": true,
	"adultDesc": null,
	"age": 25,
	"ageDesc": null,
	"birthday": 908169922000,
	"birthdayDesc": null,
	"height": 180.0,
	"heightDesc": null,
	"money": 2104.5,
	"moneyDesc": null,
	"name": "王宇",
	"nameDesc": null,
	"sex": "男",
	"sexDesc": "\u0000",
	"weight": 71.55,
	"weightDesc": null
}

2. Based on com.alibaba.fastjson.JSON

Use JSON's parseObject(String text, Class clazz) method to directly convert Json characters into Java entities corresponding to clazz, the code is as follows:

String userJson = "{\"adult\":true,\"adultDesc\":null,\"age\":25,\"ageDesc\":null,\"birthday\":908169922000,\"birthdayDesc\":null,\"height\":180.0,\"heightDesc\":null,\"money\":2104.5,\"moneyDesc\":null,\"name\":\"王宇\",\"nameDesc\":null,\"sex\":\"男\",\"sexDesc\":\"\\u0000\",\"weight\":71.55,\"weightDesc\":null}";
System.out.println("userJson:" + userJson);

User user = JSON.parseObject(userJson, User.class);
System.out.println("user:" + user);

The result of the operation is as follows:

insert image description here

3. Based on com.alibaba.fastjson.JSONObject

The parseObject method for converting Java entities in JSONObject is also from JSON and has not been rewritten. The effect is the same. The code is as follows:

String userJson = "{\"adult\":true,\"adultDesc\":null,\"age\":25,\"ageDesc\":null,\"birthday\":908169922000,\"birthdayDesc\":null,\"height\":180.0,\"heightDesc\":null,\"money\":2104.5,\"moneyDesc\":null,\"name\":\"王宇\",\"nameDesc\":null,\"sex\":\"男\",\"sexDesc\":\"\\u0000\",\"weight\":71.55,\"weightDesc\":null}";
System.out.println("userJson:" + userJson);

User user = JSONObject.parseObject(userJson, User.class);
System.out.println("user:" + user);

The result of the operation is as follows:

insert image description here

4. Based on the readValue method of com.fasterxml.jackson.databind.ObjectMapper

You need to instantiate ObjectMapper first, and then call the readValue method. The code is as follows:

String userJson = "{\"adult\":true,\"adultDesc\":null,\"age\":25,\"ageDesc\":null,\"birthday\":908169922000,\"birthdayDesc\":null,\"height\":180.0,\"heightDesc\":null,\"money\":2104.5,\"moneyDesc\":null,\"name\":\"王宇\",\"nameDesc\":null,\"sex\":\"男\",\"sexDesc\":\"\\u0000\",\"weight\":71.55,\"weightDesc\":null}";
System.out.println("userJson:" + userJson);

ObjectMapper objectMapper = new ObjectMapper();
try {
    
    
    User user = objectMapper.readValue(userJson, User.class);
    System.out.println("user:" + user);
} catch (JsonProcessingException e) {
    
    
    e.printStackTrace();
}

The result of the operation is as follows:

insert image description here

5. Based on com.google.gson.Gson

After Gson is instantiated, use the fromJson method to convert Json into a Java entity, the code is as follows:

 String userJson = "{\"adult\":true,\"adultDesc\":null,\"age\":25,\"ageDesc\":null,\"birthday\":908169922000,\"birthdayDesc\":null,\"height\":180.0,\"heightDesc\":null,\"money\":2104.5,\"moneyDesc\":null,\"name\":\"王宇\",\"nameDesc\":null,\"sex\":\"男\",\"sexDesc\":\"\\u0000\",\"weight\":71.55,\"weightDesc\":null}";
 System.out.println("userJson:" + userJson);

 Gson gson = new Gson();
 User user = gson.fromJson(userJson, User.class);
 System.out.println("user:" + user);

The running results are as follows:
insert image description here
You can see that an error is reported when the timestamp is converted to the Date type.

GsonBuilder needs to be used for instantiation, and the field of Date type should be adapted. code show as below:

String userJson = "{\"adult\":true,\"adultDesc\":null,\"age\":25,\"ageDesc\":null,\"birthday\":908169922000,\"birthdayDesc\":null,\"height\":180.0,\"heightDesc\":null,\"money\":2104.5,\"moneyDesc\":null,\"name\":\"王宇\",\"nameDesc\":null,\"sex\":\"男\",\"sexDesc\":\"\\u0000\",\"weight\":71.55,\"weightDesc\":null}";
System.out.println("userJson:" + userJson);

Gson gson = new GsonBuilder()
        .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
    
    
            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    
    
                return new Date(json.getAsJsonPrimitive().getAsLong());
            }
        })
        .create();
User user = gson.fromJson(userJson, User.class);
System.out.println("user:" + user);

run again:

insert image description here

Guess you like

Origin blog.csdn.net/studio_1/article/details/130431009