關於使用JOSN轉換java物件或集合中遇到日期格式問題(或後臺向前臺傳值,日期格式問題解決辦法)
阿新 • • 發佈:2019-02-01
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>