我有兩個POJO類:AddressInformation
和PackageInformation
(它們的getter和setter在下面的代碼中沒有指定)。Pojo to Json,如果Pojo嵌入對象
public class AddressInformation {
private Integer address_id;
private String street_name;
private String city;
private String state;
private Integer zipcode;
}
public class PackageInformation {
private Integer packageId;
private Integer packageType;
private Double packageWeight;
private AddressInformation packageSource;
private AddressInformation packageDestination;
}
我堅持使用Hibernate的類的實例,並試圖找回的PackageInformation
使用Hibernate的數據庫內容,並作爲JSON格式返回的內容。我沒有使用任何框架。我想要packagelist
其中PackageInformation的集合被轉換爲JSON。
這裏的問題是PackageInformation
對象中嵌入了AddressInformation對象。
我嘗試下面的代碼,PackageInformation集合轉換成JSON:
JSONArray json = new JSONArray();
Gson gson = new Gson();
try{
for(PackageInformation pack : packagelist){
JSONObject jsonObj = new JSONObject();
AddressInformation sourceAddress = pack.getPackageSource();
JsonElement sourceAddressJson = gson.toJsonTree(sourceAddress);
jsonObj.put("sourceAddress",sourceAddressJson);
AddressInformation destinationAddress = pack.getPackageDestination();
JsonElement destinationeAddressJson = gson.toJsonTree(destinationAddress);
jsonObj.put("destinationAddress",destinationeAddressJson);
jsonObj.put("package_id",pack.getPackageId());
jsonObj.put("package_type",pack.getPackageType());
jsonObj.put("package_weight",pack.getPackageWeight());
}
returnString = json.toString();
}catch(JSONException je){
returnString = je.toString();
}
return Response.status(200).entity(returnString).build();
但我不sourceAddress
和destinationAddress
細節嵌入作爲JSON得到JSON。相反,我得到了黑色字段:sourceAddress
和destinationAddress
細節缺失,如下面的JSON。
[
{
"sourceAddress": {},
"destinationAddress: {},
"package_id": 1,
"package_type": 1,
"package_weight": 500,
}
{
"sourceAddress": {},
"destinationAddress: {},
"package_id": 2,
"package_type": 5,
"package_weight": 700,
}
]
那麼是什麼問題? –