关于使用JOSN转换java对象或集合中遇到日期格式问题(或后台向前台传值,日期格式问题解决办法)

1,新建工具类:DateToJsonUtil    代码如下:

public class DateToJsonUtil implements JsonValueProcessor { 

    private String format = null;

    public JavaDateObjectToJsonUtil(String format) {
        super();
        this.format = format;
    }

    @Override
    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        return null;
    }

    @Override
    public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
        if (value == null) {
            return "";
        }
        if (value instanceof Date) {
            return new SimpleDateFormat(format).format((Date) value);
        }
        return value.toString();
    }
}

2,新建用户类  User    代码如下。

private String name;
    private Date birthday;
    private Integer gender;

    public String getName() {
        return name;
    }

    public Date getBirthday() {
        return birthday;
    }

    public Integer getGender() {
        return gender;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

2,再要解析的对象处调用

        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(java.util.Date.class,new DateToJsonUtil    ("yyyy-MM-dd"));
        JSONArray result = JSONObject.fromObject(user,jsonConfig);//此user为要解析的对象

3,在要解析的包含该对象的集合处调用

 JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(java.util.Date.class,new DateToJsonUtil    ("yyyy-MM-dd"));
jsonConfig.setRootClass(User.class);
        JSONArray result = JSONArray.fromObject(list,jsonConfig);//此list为要解析的集合

注意:此处JSON引入的包为: 

net.sf.json-lib

其maven依赖为:

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

猜你喜欢

转载自blog.csdn.net/pythias_/article/details/81099507