JAVA对象包含Date类型数据转Json报错处理

 

 项目A中需要将对象Case转换成json字符串,然后发送字符串消息,项目B需要将收到的json消息,转换成Case对象,再进行操作。遇到了该Case对象中有多个Date类型的字段,我又不想麻烦的将所有Date转成String类型,再生成JSON,最后鼓捣了一下午,在网上找到了解决方法。

使用net.sf.json.JSONObject进行转换(2019-04-12发现net.sf.json.JSONObject没有com.alibaba.fastjson好用,参考net.sf.json和com.alibaba.fastjson对比),pom.xml文件中引入依赖的jar包:

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

将含有Date类型的对象转成json字符串,代码如下:
package com.zz;
import java.util.Date;
import net.sf.json.JSONObject;
public class Case {
    private Integer caseId;
    private String caseName;
    private Date createDate;
    private Date appDate;
    public Integer getCaseId() {
        return caseId;
    }
    public void setCaseId(Integer caseId) {
        this.caseId = caseId;
    }
    public String getCaseName() {
        return caseName;
    }
    public void setCaseName(String caseName) {
        this.caseName = caseName;
    }
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    public Date getAppDate() {
        return appDate;
    }
    public void setAppDate(Date appDate) {
        this.appDate = appDate;
    }
    @Override
    public String toString() {
        return "Case [caseId=" + caseId + ", caseName=" + caseName
                + ", createDate=" + createDate + ", appDate=" + appDate + "]";
    }
    public static void main(String[] args) {
        Case case1 = new Case();
        case1.setCaseName("案件");
        case1.setCreateDate(new Date());
        case1.setAppDate(new Date());
        JSONObject jsonObject = JSONObject.fromObject(case1);
        String json = jsonObject.toString();
        System.out.println(json);
    }
}

执行程序,得到的结果是:

{"appDate":{"date":6,"day":4,"hours":14,"minutes":45,"month":8,"seconds":37,"time":1536216337472,"timezoneOffset":-480,"year":118},"caseId":0,"caseName":"案件","createDate":{"date":6,"day":4,"hours":14,"minutes":45,"month":8,"seconds":37,"time":1536216337472,"timezoneOffset":-480,"year":118}}
1
这不是我想要的结果啊,明明希望转成"appDate":"2018-09-06 12:00:22"这种格式的,下面就要介绍重点了。

1.java对象(含Date类型字段)转JSON
需要使用JSONConfig对象,对传入的数据,进行处理:

JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
JSONObject jsonObject = JSONObject.fromObject(case1,jsonConfig); 
JsonDateValueProcessor实现了JsonValueProcessor接口:

package com.zz;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
public class JsonDateValueProcessor implements JsonValueProcessor{
    private  String datePattern = "yyyy-MM-dd HH:mm:ss";//默认样式,可以在构造方法中修改
    public JsonDateValueProcessor() {
        super();
    }
    public JsonDateValueProcessor(String datePattern) {
        super();
        this.datePattern = datePattern;
    }
    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        try {
            if(value instanceof Date){
                SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
                Date date = (Date)value;
                return sdf.format(date);
            }
            return value == null ? null : value.toString();
        } catch (Exception e) {
            return null;
        }
    }
    public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
        return processArrayValue(value, jsonConfig);
    }
    public String getDatePattern() {
        return datePattern;
    }
    public void setDatePattern(String datePattern) {
        this.datePattern = datePattern;
    }
}

将main方法按照上述修改:

public static void main(String[] args) {
        Case case1 = new Case();
        case1.setCaseName("案件");
        case1.setCreateDate(new Date());
        case1.setAppDate(new Date());
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        JSONObject jsonObject = JSONObject.fromObject(case1,jsonConfig);
        String json = jsonObject.toString();
        System.out.println(json);
    }

执行结果如下:

{"appDate":"2018-09-06 15:03:48","caseId":0,"caseName":"案件","createDate":"2018-09-06 15:03:48"}


到这里含Date类型的对象转Json成功。参考:https://blog.csdn.net/lany1988/article/details/70257571


2.JSON转java对象(含Date类型字段)
将JSON字符串,转换成Case对象,如果直接使用:

String json="{\"appDate\":\"2018-09-06 15:03:48\",\"caseId\":0,\"caseName\":\"案件\",\"createDate\":\"2018-09-06 15:03:48\"}";
JSONObject obj = new JSONObject().fromObject(json);
Case case1=(Case)JSONObject.toBean(obj ,Case.class);

执行的结果为:

这里转换成Case对象中的时间是当前计算机的时间,不是传入的Json串中的时间,这就需要进行下面的操作了。转成对象之前,添加下面两行代码:

//日期转化格式
String[] dateFormats = new String[] {"yyyy-MM-dd HH:mm:ss"};
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));

执行结果:

对象中的日期,就是json字符串中的日期,成功。

另外,JsonConfig还有其他的使用,参考:https://www.cnblogs.com/eternalisland/p/5635985.html

报的错误如下:

java.lang.IllegalArgumentException
at java.sql.Date.getHours(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(PropertyUtils.java:1185)
at org.apache.commons.beanutils.PropertyUtils.getNestedProperty(PropertyUtils.java:772)
at org.apache.commons.beanutils.PropertyUtils.getProperty(PropertyUtils.java:801)
at net.sf.json.JSONObject._fromBean(JSONObject.java:918)
at net.sf.json.JSONObject.fromObject(JSONObject.java:168)
at net.sf.json.AbstractJSON._processValue(AbstractJSON.java:265)
at net.sf.json.JSONObject._processValue(JSONObject.java:2808)
at net.sf.json.JSONObject.processValue(JSONObject.java:2874)
at net.sf.json.JSONObject.setInternal(JSONObject.java:2889)
at net.sf.json.JSONObject.setValue(JSONObject.java:1577)
at net.sf.json.JSONObject._fromBean(JSONObject.java:934)
at net.sf.json.JSONObject.fromObject(JSONObject.java:168)
at net.sf.json.AbstractJSON._processValue(AbstractJSON.java:265)
at net.sf.json.JSONArray._processValue(JSONArray.java:2514)
at net.sf.json.JSONArray.processValue(JSONArray.java:2539)
at net.sf.json.JSONArray.addValue(JSONArray.java:2526)
at net.sf.json.JSONArray._fromCollection(JSONArray.java:1057)
at net.sf.json.JSONArray.fromObject(JSONArray.java:123)
at net.sf.json.JSONArray.fromObject(JSONArray.java:105)
at com.hysoft.order.action.OrderStudentAction.getEnterpriseList(OrderStudentAction.java:222)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:280)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:216)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值