java JSONObject serializes a java object containing data of type Date

If Date.class cannot be converted,

the following code needs to be added when using Timestamp.class jackson to convert Date
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date createTime;


The problem scenario
is that in Java, there will be such a problem: there is TIMESTAMP type data in the database, so the Bean object will have Date (java.util.Date) type parameters. When we use JSONObject to serialize the object, it will It is found that the Date property is separated into sub-objects such as year, month, day, hour, minute, second, etc., which certainly does not meet our expectations.

The solution

uses the JsonConfig provided by the json-lib package to filter attribute values ​​when processing Java objects and Json interconversion. The specific solution is as follows:

Create a date processor class
Use.

public class JsonDateValueProcessor implements JsonValueProcessor {

    private String format = "yyyy-MM-dd HH:mm:ss";

    public JsonDateValueProcessor() {
        super();
    }

    public JsonDateValueProcessor(String format) { // The format you need
        super();
        this.format = format;
    }

    @Override
    public Object processArrayValue(Object value, JsonConfig paramJsonConfig) {
        return process(value);
    }

    @Override
    public Object processObjectValue(String key, Object value, JsonConfig paramJsonConfig) {
        return process(value);
    }

    private Object process(Object value) {
        if (value instanceof Date) {
            SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
            return sdf.format(value);
        }
        return value == null ? "" : value.toString();
    }
}




handle a single bean
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
// Use Timestamp.class if Date.class cannot be converted
JSONObject json = new JSONObject();  
json.fromObject(object, jsonConfig)  


handle beanList
List<Object> objects = new ArrayList<>();
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
JSONArray taskArray = JSONArray.fromObject(objects, jsonConfig);


process map
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
JSONObject json = new JSONObject();
json.putAll(Map, jsonConfig);















Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326407018&siteId=291194637