fastjson對Date的處理

對日期的序列化:java

一種方法是經過註解json

Java代碼app

@JSONField (format="yyyy-MM-dd HH:mm:ss")  
public Date birthday;

另外一種是經過SerializeConfig:ide

Java代碼  收藏代碼this

private static SerializeConfig mapping = new SerializeConfig();  
private static String dateFormat;  
static {  
    dateFormat = "yyyy-MM-dd HH:mm:ss";  
    mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));  
}

json字符串中使用單引號:code

String text = JSON.toJSONString(object, SerializerFeature.UseSingleQuotes);orm

 

字段顯示不一樣的key:字符串

public class User {  
    @JSONField(name="ID")  
    public int getId() { ... }  
}  
   
User user = ...;  
JSON.toJSONString(user); // {"ID":001}

自定義序列化代碼示例:get

public class JsonUtil {  
    private static SerializeConfig mapping = new SerializeConfig();  
    private static String dateFormat;  
    static {  
        dateFormat = "yyyy-MM-dd HH:mm:ss";  
    }  
  
    /** 
     * 默認的處理時間 
     *  
     * @param jsonText 
     * @return 
     */  
    public static String toJSON(Object jsonText) {  
        return JSON.toJSONString(jsonText,  
                SerializerFeature.WriteDateUseDateFormat);  
    }  
  
    /** 
     * 自定義時間格式 
     *  
     * @param jsonText 
     * @return 
     */  
    public static String toJSON(String dateFormat, String jsonText) {  
        mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat));  
        return JSON.toJSONString(jsonText, mapping);  
    }  
}

自定義反序列化示例:it

先自定義一個日期解析類:

Java代碼  收藏代碼

public class MyDateFormatDeserializer extends DateFormatDeserializer {  
  
        private String myFormat;  
  
        public MyDateFormatDeserializer(String myFormat) {  
            super();  
            this.myFormat = myFormat;  
        }  
  
        @Override  
        protected <Date> Date cast(DefaultJSONParser parser, Type clazz, Object fieldName, Object val) {  
            if (myFormat == null) {  
                return null;  
            }  
            if (val instanceof String) {  
                String strVal = (String) val;  
                if (strVal.length() == 0) {  
                    return null;  
                }  
  
                try {  
                    return (Date) new SimpleDateFormat(myFormat).parse((String)val);  
                } catch (ParseException e) {  
                    throw new JSONException("parse error");  
                }  
            }  
            throw new JSONException("parse error");  
        }  
    }
相關文章
相關標籤/搜索