我从休息服务器接收此json作为响应:
{
"externalOrderId":"5cb9bc46-aaa3-43ff-bb1a-6b17443f63ea",
"shortId":null,
"createdAt":1442255497402,
"updatedAt":1442255497402,
"cart":{
"id":"gy4ectxb3db84epljzhisqrf"
}
}
然后,当我尝试使用gson.fromJson解析这个json时,我收到错误:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 201 path $.createdAt
这是我如何做到的:
public Order getOrder(String externalOrderId) throws Exception {
HttpRequest request = new HttpRequestBuilder()
.setUrl(new URI(baseURL + "/order/" + externalOrderId))
.build();
return gson.fromJson(HttpResource.getInstance().get(request).getBody(), new TypeToken<Order>(){}.getType());
}
订单对象:
private String externalOrderId;
private Long shortId;
private Date createdAt;
private Date updatedAt;
提前致谢。
答案 0 :(得分:4)
您的createdAt
和updatedAt
字段是Date
个对象,而JSON数据有数字。为了能够与数字匹配,您需要createdAt
和updatedAt
也是Long
s,然后将它们转换为Date
个对象。< / p>
答案 1 :(得分:0)
试试这个(参见Order.java中的toString和longToDate方法) -
<强> Cart.java 强>
public class Cart {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return "Cart [id=" + id + "]";
}
}
<强> Order.java 强>
import java.util.Date;
public class Order {
private String externalOrderId;
private Long shortId;
private Long createdAt;
private Long updatedAt;
private Cart cart;
public String getExternalOrderId() {
return externalOrderId;
}
public void setExternalOrderId(String externalOrderId) {
this.externalOrderId = externalOrderId;
}
public Long getShortId() {
return shortId;
}
public void setShortId(Long shortId) {
this.shortId = shortId;
}
public Long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Long createdAt) {
this.createdAt = createdAt;
}
public Long getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Long updatedAt) {
this.updatedAt = updatedAt;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
private Date longToDate(Long dt) {
return new Date(dt);
}
@Override
public String toString() {
return "Order [externalOrderId=" + externalOrderId + ", shortId="
+ shortId + ", createdAt=" + longToDate(createdAt) + ", updatedAt="
+ longToDate(updatedAt) + ", cart=" + cart + "]";
}
}
<强> Main.java 强>
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.Order;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
public static void main(String[] args) {
String j = "{\"externalOrderId\":\"5cb9bc46-aaa3-43ff-bb1a-6b17443f63ea\",\"shortId\":null,\"createdAt\":1442255497402,\"updatedAt\":1442255497402,\"cart\":{\"id\":\"gy4ectxb3db84epljzhisqrf\"}}";
Order r = gson.fromJson(j, Order.class);
System.out.println(r);
}
}
<强>结果强>
Order [externalOrderId=5cb9bc46-aaa3-43ff-bb1a-6b17443f63ea, shortId=null, createdAt=Tue Sep 15 00:01:37 IST 2015, updatedAt=Tue Sep 15 00:01:37 IST 2015, cart=Cart [id=gy4ectxb3db84epljzhisqrf]]