• Json-lib


    使用 JSON-lib 将 java.util.Date 对象直接转换成 JSON 字符串时,得到的通常不是想要格式:

    System.out.println(JSONSerializer.toJSON(new Date()));
    // {"date":24,"day":3,"hours":12,"minutes":39,"month":5,"seconds":46,"time":1435120786584,"timezoneOffset":-480,"year":115}

    JavaBean 转 JSON

    JsonValueProcessor jsonValueProcessor = new JsonValueProcessor() {
        private final String DATE_FORMAT = "yyyy-MM-dd";
        @Override
        public Object processObjectValue(String key, Object value, JsonConfig config) {
            if (value == null) {
                return "";
            }
            if (value instanceof Date) {
                return new SimpleDateFormat(DATE_FORMAT).format((Date) value);
            }
            return value.toString();
        }
        @Override
        public Object processArrayValue(Object value, JsonConfig config) {
            return null;
        }
    };
    
    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.registerJsonValueProcessor(Date.class, jsonValueProcessor);
    Student stud = new Student("1001", "huey", 'M', new Date());
    String jsonStr = JSONSerializer.toJSON(stud, jsonConfig).toString();
    System.out.println(jsonStr);    // {"birthday":"2015-06-24","gender":"M","studName":"huey","studNo":"1001"}

    JSON 转 JavaBean

    String jsonStr = "{'studNo':'1001','studName':'huey','gender':'M','birthday':'2014-04-13'}";
    JSONObject jsonObj = JSONObject.fromObject(jsonStr);
    JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[]{"yyyy-MM-dd"}));
    Student stud = (Student) JSONObject.toBean(jsonObj, Student.class);
    System.out.println(stud);    // Student(studNo=1001, studName=huey, gender=M, birthday=Sun Apr 13 00:00:00 CST 2014)

    JavaBean 定义

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Student {
        private String studNo;
        private String studName;
        private char gender;
        private Date birthday;    
    }
  • 相关阅读:
    Gartner:当商业智能成熟度低时,如何加快分析采用率
    年薪50万的大数据分析师养成记
    数据化管理在餐饮业中的应用
    linux下查看本机socket端口详细信息
    nginx模块编程之获取客户ip及端口号
    大小端模式转换函数
    Nginx代码调试——gdb工具
    Nginx入门之两种handler函数的挂载方式
    Nginx重要结构request_t解析之http请求的获取
    Nginx_handler模块发开(hello模块结构解析)
  • 原文地址:https://www.cnblogs.com/huey/p/4597242.html
Copyright © 2020-2023  润新知