fastjson对Date的处理

前端之家收集整理的这篇文章主要介绍了fastjson对Date的处理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

对日期的序列化:

一种方法是通过注解

Java代码

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


另一种是通过SerializeConfig:

Java代码

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


json字符串中使用单引号:

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

字段显示不同的key:

  1. public class User {
  2. @JSONField(name="ID")
  3. public int getId() { ... }
  4. }
  5. User user = ...;
  6. JSON.toJSONString(user); // {"ID":001}


自定义序列化代码示例:

  1. public class JsonUtil {
  2. private static SerializeConfig mapping = new SerializeConfig();
  3. private static String dateFormat;
  4. static {
  5. dateFormat = "yyyy-MM-dd HH:mm:ss";
  6. }
  7. /**
  8. * 默认的处理时间
  9. *
  10. * @param jsonText
  11. * @return
  12. */
  13. public static String toJSON(Object jsonText) {
  14. return JSON.toJSONString(jsonText,SerializerFeature.WriteDateUseDateFormat);
  15. }
  16. /**
  17. * 自定义时间格式
  18. *
  19. * @param jsonText
  20. * @return
  21. */
  22. public static String toJSON(String dateFormat,String jsonText) {
  23. mapping.put(Date.class,new SimpleDateFormatSerializer(dateFormat));
  24. return JSON.toJSONString(jsonText,mapping);
  25. }
  26. }


自定义反序列化示例:

自定义一个日期解析类:

Java代码

  1. public class MyDateFormatDeserializer extends DateFormatDeserializer {
  2. private String myFormat;
  3. public MyDateFormatDeserializer(String myFormat) {
  4. super();
  5. this.myFormat = myFormat;
  6. }
  7. @Override
  8. protected <Date> Date cast(DefaultJSONParser parser,Type clazz,Object fieldName,Object val) {
  9. if (myFormat == null) {
  10. return null;
  11. }
  12. if (val instanceof String) {
  13. String strVal = (String) val;
  14. if (strVal.length() == 0) {
  15. return null;
  16. }
  17. try {
  18. return (Date) new SimpleDateFormat(myFormat).parse((String)val);
  19. } catch (ParseException e) {
  20. throw new JSONException("parse error");
  21. }
  22. }
  23. throw new JSONException("parse error");
  24. }
  25. }
转自:http://my.oschina.net/u/1444624/blog/375740

猜你在找的Json相关文章