【发布时间】:2014-05-15 11:57:48
【问题描述】:
我正在使用 RestTemplete 从 rest api 获取 json 数据,我正在使用 Gson 将数据从 json 格式解析为 Object
Gson gson = new Gson();
restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new GsonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
List<Appel> resultList = null;
resultList = Arrays.asList(restTemplate.getForObject(urlService, Appel[].class));
但是我遇到了这个日期问题,我该怎么办..
Could not read JSON: 1382828400000; nested exception is com.google.gson.JsonSyntaxException: 1382828400000
我的 Pojo 体内包含其他 pojos
public class Appel implements Serializable {
private Integer numOrdre;
private String reference;
private String objet;
private String organisme;
private Double budget;
private Double caution;
private Date dateParution;
private Date heureParution;
private Date dateLimite;
private Date heureLimite;
private List<Support> supportList;
private Ville villeid;
private Categorie categorieid;
public Appel() {
}
public Appel(Integer numOrdre, String reference, String objet, String organisme, Date dateParution, Date heureParution, Date dateLimite) {
this.numOrdre = numOrdre;
this.reference = reference;
this.objet = objet;
this.organisme = organisme;
this.dateParution = dateParution;
this.heureParution = heureParution;
this.dateLimite = dateLimite;
}
这是我的 API 返回的 json
[
{
"numOrdre": 918272,
"reference": "some text",
"objet": "some text",
"organisme": "some text",
"budget": 3000000,
"caution": 3000000,
"dateParution": 1382828400000,
"heureParution": 59400000,
"dateLimite": 1389657600000,
"heureLimite": 34200000,
"supportList":
[
{
"id": 1,
"nom": "some text",
"dateSupport": 1384732800000,
"pgCol": "013/01"
},
{
"id": 2,
"nom": "some text",
"dateSupport": 1380236400000,
"pgCol": "011/01"
}
],
"villeid":
{
"id": 2,
"nom": "Ville",
"paysid":
{
"id": 1,
"nom": "Pays"
}
},
"categorieid":
{
"id": 1,
"description": "some text"
}
},
.....
]
【问题讨论】:
-
你的 json 是什么样的?你的pojo是什么样的?
-
您正试图投射一个长日期。
-
这些值,
1384732800000,看起来像时间戳。 Gson 未设置为解析带有时间戳的日期。您必须使用自定义TypeAdapter对其进行配置。 -
您需要使用 GsonBuilder 并传递日期格式化程序字符串,以便 Gson 知道如何解析您的日期。这是一个示例:stackoverflow.com/a/34187419/1103584