【发布时间】:2020-02-03 07:36:19
【问题描述】:
我正在尝试反序列化 Java 中的 JSON 对象,但 gson.fromJson() 似乎不起作用。它在反序列化后给出null 值。
我有一个这样的 json 响应:
{
"master": [{
"data": {
"getStoreItem": {
"gtin": "84",
"storeId": "49",
"locations": {
"salesfloor": [{
"aisle": "5",
"aisleDesc": "5"
}]
},
"pricing": {
"retailPrice": 11.28,
"hoRetailPrice": null
},
"basicInfo": {
"itemNumber": 87,
"departmentNumber": 1
},
"inventory": {
"onHandQuantity": 358,
"inTransitQuantity": 0
},
"restrictions": {
"isAssociateDiscountable": false
},
"itemAssociatedGtins": [{
"gtin": "847"
}]
}
}
}, {
"data": {
"getStoreItem": {
"gtin": "97",
"storeId": "4",
"locations": {
"salesfloor": [{
"aisle": "1",
"aisleDesc": "1"
}]
},
"pricing": {
"retailPrice": 19.98,
"hoRetailPrice": null
},
"basicInfo": {
"itemNumber": 871,
"departmentNumber": 1
},
"inventory": {
"onHandQuantity": 56,
"inTransitQuantity": 0
},
"restrictions": {
"isAssociateDiscountable": false
},
"itemAssociatedGtins": [{
"gtin": "9754610200"
}]
}
}
}]
}
我有一个像这样的Master.java 类-
import java.util.List;
public class Master {
List<Data> data;
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
public static class Data {
private GetStoreItem getStoreItem;
public GetStoreItem getGetStoreItem() {
return getStoreItem;
}
public void setGetStoreItem(GetStoreItem getStoreItem) {
this.getStoreItem = getStoreItem;
}
public static class GetStoreItem {
private String gtin;
private String storeId;
public String getGtin() {
return gtin;
}
public void setGtin(String gtin) {
this.gtin = gtin;
}
public String getStoreId() {
return storeId;
}
public void setStoreId(String storeId) {
this.storeId = storeId;
}
}
}
}
当我在做的时候:
Master m = gson.fromJson(json, Master.class);
m 包含:
data: null
无法弄清楚我哪里出错了。
【问题讨论】:
-
也许您可以尝试转义您的 json 字符串?我对其进行了测试以查看会发生什么,但似乎 Gson 在在线 IDE 中无法使用,但它确实摆脱了
unclosed string literal错误。 -
@Still_learning 我没有对 json 进行硬编码。我收到来自外部服务的响应。 :)
-
@Still_learning 我尝试像这样对 json 进行硬编码-
"{\"master\": [{\"getStoreItem\": {\"gtin\": \"84\",\"storeId\": \"49\"}}]}"仍然遇到同样的问题。也许问题可能出在嵌套对象上? -
我的意思是用这样的换行符转义 json:
"{\n\"Main\": [{\n \"data\": {\n\"getStoreItem\":{\\"gtin\": \"84\", ...我做到了here -
@Still_learning 现在可以使用了。不得不稍微修改一下课程。感谢您调查它。 :)
标签: json gson json-deserialization