json格式化
#post请求json格式
{"results": [{
"vin": "1888",
"pushId": "40",
"pushState": 1,
"arrivalTime": "2018-03-10 21:02:22"
}, {
"vin": "03064",
"pushId": "40",
"pushState": 1,
"arrivalTime": "2018-03-10 21:02:22"
}
]
}
- 现在想取得results里的内容:
Map<String,Object> map=JSON.parseObject(body,Map.class);
String results=map.get("results");
- 会直接报错.错误为:
java.lang.ClassCastException: com.alibaba.fastjson.JSONArray cannot be cast to java.lang.String
- 正确写法为:
Map<String,String> map=JSON.parseObject(body,new TypeReference<Map<String, String>>(){});
String results=map.get("results");
##fastjson date时间格式化:
JSON.toJSONStringWithDateFormat(pushContent, "yyyy-MM-dd HH:mm:ss")
自动把Date时间格式为yyyy-MM-dd HH:mm:ss格式 .
package com.abupdate.carpush.bean;
import com.abupdate.carpush.common.BaseParams;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
import java.util.List;
/**
* @author allen
* @date 20/03/2018
*/
public class PushContent {
private String token;
private List<String> vins;
private String content;
private String pushId;
@JsonFormat(shape = JsonFormat.Shape.STRING,pattern = BaseParams.TIME_PATTERN_FORMAT,timezone = "GMT+8")
private Date endTime;
public List<String> getVins() {
return vins;
}
public void setVins(List<String> vins) {
this.vins = vins;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPushId() {
return pushId;
}
public void setPushId(String pushId) {
this.pushId = pushId;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
转换
POJO类型转string
TrainNoBO trainNoBO=new TrainNoBO();
String json= JSONObject.toJSONString(trainNoBO);
string转POJO
TrainNoBO trainNoBO1 = JSON.parseObject(s, TrainNoBO.class);
取某一个字段
JSONObject jsonObject = JSON.parseObject(s);
String fromCity = jsonObject.getString("fromCity");
string转list
List<String> array= JSON.parseArray(a,String.class);
for(String tmp: array){
System.out.println(tmp);
}