日期:2014-05-16  浏览次数:20472 次

fastjson对Date的处理

对日期的序列化:

一种方法是通过注解

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

另一种是通过SerializeConfig:

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字符串中使用单引号:

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

?

字段显示不同的key:

?

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

?

类的反序列化 JavaBean:

?

String text = ...; // {"r":255,"g":0,"b":0,"alpha":255}
Color color = JSON.parseObject(text, Color.class);

?

数组:

?

String text = ...; // [{ ... }, { ... }]
List<User> users = JSON.parseArray(text, User.class);

?

泛型:

String text = ...; // {"name":{"name":"ljw",age:18}}
Map<String, User> userMap = JSON.parseObject(text, new TypeReference<Map<String, User>>() {});

?

自定义序列化代码示例:

?

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);
    }
}

?

自定义反序列化示例:

先自定义一个日期解析类:

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");
        }
    }

?

public class User {

    public String name;
    public int height;

    @JSONField(name = "com-google-com")
    public void setName(String name) {
        this.name