JSONObject的内容为:
{"userId":"A000004FFDCE14","userName":"好好干g","userMp":"1820257596","clientName":"风格","regDate":"2016-07-05 00:00:00","startDate":"2016-07-05 00:00:00","endDate":"2017-09-05 00:00:00","times":15458,"master":"master","yesorno":3}]
List listpre = PreApplyConvertEntity.secectlistinfo();
Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter())
.setDateFormat("yyyy-MM-dd HH:mm:ss").create();
String json = gson.toJson(listpre);
System.out.println(json);
JSONArray ja = JSONArray.fromObject(json);
for (int i = 0; i < ja.size(); i++) {
JSONObject jo = ja.getJSONObject(i);
String[] dateFormats = new String[] {"yyyy-MM-dd HH:mm:ss" };
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));
PreparedInfo person = (PreparedInfo) JSONObject.toBean(jo, PreparedInfo.class);
System.out.println(person);
1 DateTypeAdapter类:2 public class DateTypeAdapter implements JsonSerializer ,JsonDeserializer{3 private final SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");4 @Override5 public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throwsJsonParseException {6 //TODO Auto-generated method stub
7 if (!(json instanceofJsonPrimitive)) {8 throw new JsonParseException("The date should be a string value");9 }10
11 try{12 returndateFormate.parse(json.getAsString());13
14
15 } catch(ParseException e) {16 throw newJsonParseException(e);17 }18
19
20
21 }22
23 @Override24 publicJsonElement serialize(Date src, Type arg1, JsonSerializationContext arg2) {25 String dateFormatAsString = dateFormate.format(newDate(src.getTime()));26 return newJsonPrimitive(dateFormatAsString);27
28 }29
30 }
View Code
其中 :List listpre = PreApplyConvertEntity.secectlistinfo();
Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
String json = gson.toJson(listpre);
将List集合对象转换成jsonstring 对象!
还有:String[] dateFormats = new String[] {"yyyy-MM-dd HH:mm:ss" };
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));
PreparedInfo person = (PreparedInfo) JSONObject.toBean(jo, PreparedInfo.class);
解决不要这段代码时转换并不抛出例外,而是在日志中打出以下警告信息: Can't transform property 'birthday' from java.lang.String into java.util.Date. Will register a default Morpher 的解决办法
最后 有时我们想将日期保存到数据库时用 java.util.Date 就会出错,一定要用java.sql.Date 这是在使用 JDBC 的情况下,在这种情况下就要将 java.util.Date 转换为 java.sql.Date,下面就是示例代码 java.util.Date utilDate = new java.util.Date(); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());