I have two POJO classes: AddressInformationand PackageInformation(with their getters and setters that are not listed in the code below).
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;
}
I am saving instances of classes using hibernate and trying to get the contents PackageInformationfrom the database using sleep mode and return the contents in JSON format. I do not use any frameworks.
Session session = HibernateUtils.getSessionFactory().openSession();
List<PackageInformation> packagelist = null;
tx = session.beginTransaction();
packagelist = session.createQuery("FROM PackageInformation").list();
tx.commit();
session.close();
I need packagelistone that has a PackageInformation set to convert to JSON.
The trap is that the object PackageInformationhas address information built into it.
I tried the code below to convert the PackageInformation collection to 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();
JSON sourceAddress destinationAddress , 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,
}
]