您可以嘗試走出標準執行Java API for JSON processing這是J2EE一部分。
爲了您List<DeviceOrder> devLst
,定義bean:
public class DeviceOrder implements Serializable {
private static final long serialVersionUID = 893438341L;
public DeviceOrder() {
}
public DeviceOrder(int id, String desc, Date date) {
this.id = id;
this.desc = desc;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((desc == null) ? 0 : desc.hashCode());
result = prime * result + id;
return result;
}
private int id;
private String desc;
private Date date;
}
然後用:
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<DeviceOrder> devLst = new ArrayList<DeviceOrder>() {
{
add(new DeviceOrder(1, "order 1", sdf.parse("2010-05-01")));
add(new DeviceOrder(2, "order 2", sdf.parse("2010-06-01")));
add(new DeviceOrder(3, "order 3", sdf.parse("2010-07-01")));
}
};
DeviceOrder[] devArr = devLst.toArray(new DeviceOrder[devLst.size()]);
JsonArrayBuilder devArrBuilder = Json.createArrayBuilder();
for (DeviceOrder devOrder : devArr) {
JsonObjectBuilder jsonObject = Json.createObjectBuilder()
.add("id", devOrder.getId())
.add("desc", devOrder.getDesc())
.add("date", sdf.format(devOrder.getDate()));
devArrBuilder.add(jsonObject);
}
JsonArray jsonArray = devArrBuilder.build();
Map<String, Object> prop = new HashMap<String, Object>() {
{
put(JsonGenerator.PRETTY_PRINTING, true);
}
};
JsonWriter jsonWriter = Json.createWriterFactory(prop).createWriter(System.out);
jsonWriter.writeArray(jsonArray);
jsonWriter.close();
輸出應該是:
[
{
"id":1,
"desc":"order 1",
"date":"2010-05-01"
},
{
"id":2,
"desc":"order 2",
"date":"2010-06-01"
},
{
"id":3,
"desc":"order 3",
"date":"2010-07-01"
}
]
你Map<Member, Map<CustomerVO, Set<Vehicle>>> map
可以降低到List
並以類似的方式JSON。
你有序列化POJO的? –
是的對象被序列化。 – changeme
強烈建議:考慮使用[javax.json](https://jsonp.java.net/) – FoggyDay