【发布时间】:2017-10-16 16:23:28
【问题描述】:
在我的Java Handler 类中,我尝试使用Gson.toJson() 方法来返回存根数据作为响应。
我遇到的问题是Gson.toJson() 方法没有正确映射我的Json,它所做的是提供一个具有空字段和默认值的对象。
存根 Json:
{
"order": [{
"from": "exampleCustomer",
"alternateOrderIdentifier": [{
"type": "Service Type",
"value": "order"
},
{
"type": "Product Type",
"value": "book"
}
],
"orderIdentifier": "order123"
}]
}
Java POJO:
public class Order {
private String actionCode = "Create";
private AlternateOrderIdentifier[] alternateOrderIdentifier;
private String from;
private String status = "Open";
private String orderIdentifier;
private String customerId;
public Order() {
}
//getters and setters
}
Java Handler 方法:
@GET
@Path("/my/path/order")
public Response getOrderDetails(@QueryParam("orderId") String orderIdentifier
) throws IOException {
Order order = new Order();
try {
InputStream is = StubOrderHandler.class.getResourceAsStream("/my/path/to/stubOrder.json");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
Gson gson = new Gson();
order = gson.fromJson(bufferedReader, Order.class);
} catch (Exception e) {
}
return ResponseBuilder.anOKResponse().withEntity(order).build();
}
我在响应中返回的订单对象字段如下
actionCode = "Create"
alternateOrderIdentifier = null
from - null
status = "Open"
orderIdentifier = null
customerId = null
显然对象没有被正确映射。
我期待例如CustomerId 为空,因为我没有将它添加到存根 Json。但我不确定为什么我会得到空值,例如orderIdentifier 和alternateOrderIdentifier?
我确定json文件的路径和文件名是正确的。可能是什么问题?
【问题讨论】:
-
你能改变存根吗?对象和存根 json 映射不正确
-
我已经检查了存根是有效的 json?字段的顺序是否重要?我还应该进行哪些其他更改?
-
你的 JSON 和你的 POJO 不匹配。
-
@chsdk 我很难看到 POJO 和 Json 之间到底有什么不匹配的?
-
查看与您的对象匹配的实际 json 的最佳方法是将其序列化...gson.toJson(order),这也是我在回答中使用的
标签: java json gson inputstream