//msg 是JSON字符串
String msg = "";
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(msg,Map.class);
//可用于将任何Java值序列化为String的方法。在功能上等同于调用 writeValue(Writer,Object)与StringWriter 和构建字符串,但更有效。
mapper.writeValueAsString(map);
jackson 将String的json文件转换为对象
ObjectMapper mapper = new ObjectMapper();
String json = "{\"dataType\":\"2\",\"newFlag\":\"1\",\"data\":[{\"storeCode\":\"809\",\"businessDay\":\"2019-08-11\",\"orderId\":\"100000412\",\"orderStatus\":2}]}";
OrderInfo orderInfo=mapper.readValue(json,OrderInfo.class);
System.out.println(orderInfo.toString());
实体类
@JsonIgnoreProperties(ignoreUnknown = true)
public class OrderInfo {
private String newFlag;
private List<OrderData> data;
public String getNewFlag() {
return newFlag;
}
public void setNewFlag(String newFlag) {
this.newFlag = newFlag;
}
public List<OrderData> getData() {
return data;
}
public void setData(List<OrderData> data) {
this.data = data;
}
@Override
public String toString() {
return "OrderInfo{" +
"newFlag='" + newFlag + '\'' +
", data=" + data +
'}';
}
public class OrderData {
private String storeCode;
private String businessDay;
private String orderId;
private String orderStatus;
public String getStoreCode() {
return storeCode;
}
public void setStoreCode(String storeCode) {
this.storeCode = storeCode;
}
public String getBusinessDay() {
return businessDay;
}
public void setBusinessDay(String businessDay) {
this.businessDay = businessDay;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
@Override
public String toString() {
return "data{" +
"storeCode='" + storeCode + '\'' +
", businessDay='" + businessDay + '\'' +
", orderId='" + orderId + '\'' +
", orderStatus='" + orderStatus + '\'' +
'}';
}
}
jackson String类型转换为对象类型,需要字段名匹配,传入name,变量名命名就是name,get方法必须是getName(); 如果json串中的字段不完全需要映射到实体类中,则可在实体类上加上
@JsonIgnoreProperties(ignoreUnknown = true)
注解,时jackson在转换时忽略不能映射的字段。
Jackson将复杂String信息解析为map
Map<String, Object> dataMap = null;
try {
dataMap = mapper.readValue(json, Map.class);
} catch (IOException e) {
e.printStackTrace();
}
//获取json中的数组,转为List<Map<String,Object>>类型
List<Map<String,Object>> data= (List<Map<String,Object>>) dataMap.get("data");
for (Map<String,Object> map : data){
//获取数组的属性存入对象
OrderData.setTransTime(map.get("transTime"));
}
网友评论