利用JSONArray转换list
定义的model:
1 package com.yds.model; 2 3 import java.util.Date; 4 5 6 7 public class DeviceHistory { 8 9 private int id; 10 private Date acq_time; 11 12 13 14 public int getId() { 15 return id; 16 } 17 public void setId(int id) { 18 this.id = id; 19 } 20 public String getDevice_id() { 21 return device_id; 22 } 23 24 public Date getAcq_time() { 25 return acq_time; 26 } 27 public void setAcq_time(Date acq_time) { 28 this.acq_time = acq_time; 29 } 30 31 }
测试类:
import java.util.ArrayList; import java.util.Date; import java.util.List; import net.sf.json.JSONArray; import com.yds.model.DeviceHistory;
public class Test { public static void main(String[] args) { List<DeviceHistory> list = new ArrayList<DeviceHistory>(); DeviceHistory dh = new DeviceHistory(); dh.setAcq_time(new Date()); list.add(dh); JSONArray json =JSONArray.fromObject(list); System.out.println(json.toString()); } }
打印结果为:
[{"acq_time":{"date":18,"day":2,"hours":21,"minutes":7,"month":7,"seconds":27,"time":1439903247640,"timezoneOffset":-480,"year":115},"id":0}]
开始时我用的JSONArray在action中进行list转换 发现到JSONArray json =JSONArray.fromObject(list);就执行不下去了,经过一番调发现是时间转换时出了问题,就换了jackson进行转换
测试类:
1 import java.io.IOException; 2 import java.util.ArrayList; 3 import java.util.Date; 4 import java.util.List; 5 6 import org.codehaus.jackson.JsonGenerationException; 7 import org.codehaus.jackson.map.JsonMappingException; 8 import org.codehaus.jackson.map.ObjectMapper; 9 import com.yds.model.DeviceHistory; 10 11 public class Test { 12 public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException { 13 List<DeviceHistory> list = new ArrayList<DeviceHistory>(); 14 DeviceHistory dh = new DeviceHistory(); 15 dh.setAcq_time(new Date()); 16 list.add(dh); 17 ObjectMapper objectMapper = new ObjectMapper(); 18 String json = objectMapper.writeValueAsString(list); 19 System.out.println(json); 20 } 21 22 }
打印结果为:
[{"id":0,"acq_time":1439904893237}] 这样action也能执行下去了