Object to JSON date format and keep the data order and Value is empty Key still returns

1. Business background

(1) The project panorama is not configurable, and the front-end page of the process modification return field also needs to be modified accordingly, and the scalability is poor.
(2) To be configurable, the fields need to be taken from the process, but the key sequence of JSON data returned by AJAX is not consistent with the order of fields returned in the process

2. Cause analysis

When fastjson converts Object to JSON, the bottom layer uses HashMap. If it is in order, it needs to be LinkedHashMap. Check the source code to find out

 public JSONObject(int initialCapacity, boolean ordered){
    
    
        if (ordered) {
    
    
            map = new LinkedHashMap<String, Object>(initialCapacity);
        } else {
    
    
            map = new HashMap<String, Object>(initialCapacity);
        }
    }

However, how to convert Object to JSON string? Checking the source code did not find the conversion method, but the standard Map type is returned in the process, so paste the following code

3. Solve the code

SerializeConfig serializeConfig = new SerializeConfig();
ObjectSerializer serializer = new SimpleDateFormatSerializer(DateUtils.format());
serializeConfig.put(Timestamp.class, serializer);
serializeConfig.put(java.sql.Date.class, serializer);
serializeConfig.put(Date.class, serializer);

if (obj instanceof Map){
    
    
    JSONObject jsonObject = new JSONObject(16, true);
    jsonObject.putAll((Map) obj);
    // 输出key时是否使用双引号,默认为true
    // 是否输出值为null的字段,默认为false
    result = JSON.toJSONStringZ(jsonObject, serializeConfig, SerializerFeature.QuoteFieldNames, SerializerFeature.WriteMapNullValue);
}

Guess you like

Origin blog.csdn.net/SJshenjian/article/details/130188573