• 带日期的bean转为json(bean->JSON)


    示例代码:


    JsonBean bean = new JsonBean();
    bean.setName("NewBaby");
    bean.setAge(1);
    bean.setBorn(new Date());
    jo = JSONObject.fromObject(bean);
    System.out.println("bean->json:" + jo.toString());


    打印结果:bean->json:{"age":1,"born":{"date":10,"day":3,"hours":14,"minutes":14,"month":2,"seconds":1,"time":1268201641228,"timezoneOffset":-480,"year":110},"name":"NewBaby"}  

    这时你会发现它把bean对象里的util.Date这个类型的所有属性一一转换出来。在实际运用过程中,大多数情况下我们希望能转化为yyyy-MM-dd这种格式,下面就讲一讲如何实现。

    首先要写一个新的类JsonDateValueProcessor如下:


    public class JsonDateValueProcessor implements JsonValueProcessor {
       
        private String datePattern = "yyyy-MM-dd";
       
        public JsonDateValueProcessor() {
            super();
        }
       
        public JsonDateValueProcessor(String format) {
            super();
            this.datePattern = format;
        }
       
        public Object processArrayValue(Object value, JsonConfig jsonConfig) {
            return process(value);
        }
       
        public Object processObjectValue(String key, Object value,
                JsonConfig jsonConfig) {
            return process(value);
        }
       
        private Object process(Object value) {
            try {
                if (value instanceof Date) {
                    SimpleDateFormat sdf = new SimpleDateFormat(datePattern,
                            Locale.UK);
                    return sdf.format((Date) value);
                }
                return value == null ? "" : value.toString();
            } catch (Exception e) {
                return "";
            }
        }
       
        public String getDatePattern() {
            return datePattern;
        }
       
        public void setDatePattern(String pDatePattern) {
            datePattern = pDatePattern;
        }
    }
     
    测试代码:

    JsonBean bean = new JsonBean();
    bean.setName("NewBaby");
    bean.setAge(1);
    bean.setBorn(new Date());

    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor());

    JSONObject jo = JSONObject.fromObject(bean, jsonConfig);
    System.out.println("bean->json:" + jo.toString());

    打印结果:bean->json:{"age":1,"born":"2010-03-10","name":"NewBaby"}
    这就能得到我们想要的结果了。
  • 相关阅读:
    Android Eclipse真机调试 过滤器filter没有显示
    Maven in 5 Minutes(Windows)
    接触JETM
    使用mobile.changePage()时出现的问题(转)
    jQuery Mobile页面跳转后未加载外部JS(转)
    iDempiere VS ADempiere
    为Drupal7.22添加富编辑器 on Ubuntu 12.04
    说说iDempiere = OSGi + ADempiere的OSGi
    购买阿里云云服务器( 最小配置)
    安装Drupal7.12升级至7.22
  • 原文地址:https://www.cnblogs.com/yhtboke/p/6165169.html
Copyright © 2020-2023  润新知