怎么样将复杂的json字符串转java对象?
json字符串:
{“createTime”:”2016-07-05 08:08:08″,”cityName”:”杭州”,”orderItems”:”[{“skuId”:”1008604″,”count”:2,”unitPrice”:8.88},{“skuId”:”1008605″,”count”:1,”unitPrice”:6.66}]”}]
javaBean:
public class Order{
private String cityName;
private String createTime;
private List<OrderItem> orderItemList;
// 省略getter和setter方法。
}
工具:fastjson
使用Order Order = (Order) JSON.parseObject(data, Order.class);该方法转换发现orderItemList为空,假如处理才能正确解析让orderItemList不为空呢?
json字符串:
{“createTime”:”2016-07-05 08:08:08″,”cityName”:”杭州”,”orderItems”:”[{“skuId”:”1008604″,”count”:2,”unitPrice”:8.88},{“skuId”:”1008605″,”count”:1,”unitPrice”:6.66}]”}]
javaBean:
public class Order{
private String cityName;
private String createTime;
private List<OrderItem> orderItemList;
// 省略getter和setter方法。
}
工具:fastjson
使用Order Order = (Order) JSON.parseObject(data, Order.class);该方法转换发现orderItemList为空,假如处理才能正确解析让orderItemList不为空呢?
解决方案
40
package com.imooc.tag; import com.alibaba.fastjson.JSON; public class TagMain { public static void main(String[] args) { Order order = JSON.parseObject("{"createTime":"2016-07-05 08:08:08","cityName":"杭州","orderItems":[{"skuId":"1008604","count":2,"unitPrice":8.88},{"skuId":"1008605","count":1,"unitPrice":6.66}]}", Order.class); for (OrderItem orderItem : order.getOrderItems()) { System.out.println(orderItem); } } }
package com.imooc.tag; import java.util.List; public class Order { private String cityName; private String createTime; private List<OrderItem> orderItems; public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public List<OrderItem> getOrderItems() { return orderItems; } public void setOrderItems(List<OrderItem> orderItems) { this.orderItems = orderItems; } }
package com.imooc.tag; public class OrderItem { private String skuId; private Integer count; private Integer unitPrice; public String getSkuId() { return skuId; } public void setSkuId(String skuId) { this.skuId = skuId; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public Integer getUnitPrice() { return unitPrice; } public void setUnitPrice(Integer unitPrice) { this.unitPrice = unitPrice; } @Override public String toString() { return "OrderItem [skuId=" + skuId + ", count=" + count + ", unitPrice=" + unitPrice + "]"; } }