I'm quite new to spring and I'm using spring entitymanager.createquery to make query and get the result from database.
So when make a http get this method executes to get all the patient name
public List<PatientModel> fetchallpatients (){
Query q = entityManager.createNativeQuery("select * from patient p ");
List <PatientModel> patientList=q.getResultList();
System.out.println(patientList);
return patientList;
}
it is returning
[[
1,
"patientname",
"patientphone",
"patientgender",
"patientinsurance",
"patientage",
"patientdiagnosis",
"patientaddreq",
"patientemr"
],
[
2,
"test",
"patientphone",
"patientgender",
"patientinsurance",
"patientage",
"patientdiagnosis",
"patientaddreq",
"patientemr"
],
[
3,
"react",
"12312",
"male",
"react",
"56",
"dsa",
"ads",
"das"
],
[
4,
"sign",
"asd",
"male",
"react",
"56",
"Diagnose 2",
"Ventilator",
"on"
],
[
5,
"good",
"3213",
"male",
"react",
"56",
"Diagnose 3",
"ICU",
"on"
] ]
Front end I'm using react and I need this data to be in JSON format.
I have a POJO class for corresponding table:
package io.login.model;
import java.io.Serializable;
public class PatientModel {
String patientname;
String patientage;
String patientgender;
String patientinsurance;
String patientphone;
String patientaddreq;
String patientemr;
public String getPatientname() {
return patientname;
}
public void setPatientname(String patientname) {
this.patientname = patientname;
}
public String getPatientage() {
return patientage;
}
public void setPatientage(String patientage) {
this.patientage = patientage;
}
public String getPatientgender() {
return patientgender;
}
public void setPatientgender(String patientgender) {
this.patientgender = patientgender;
}
public String getPatientinsurance() {
return patientinsurance;
}
public void setPatientinsurance(String patientinsurance) {
this.patientinsurance = patientinsurance;
}
public String getPatientphone() {
return patientphone;
}
public void setPatientphone(String patientphone) {
this.patientphone = patientphone;
}
public String getPatientdiagnosis() {
return patientdiagnosis;
}
public void setPatientdiagnosis(String patientdiagnosis) {
this.patientdiagnosis = patientdiagnosis;
}
public String getPatientaddreq() {
return patientaddreq;
}
public void setPatientaddreq(String patientaddreq) {
this.patientaddreq = patientaddreq;
}
public String getPatientemr() {
return patientemr;
}
public void setPatientemr(String patientemr) {
this.patientemr = patientemr;
}
String patientdiagnosis;
public PatientModel(String patientname, String patientage, String patientgender, String patientinsurance, String patientphone, String patientdiagnosis, String patientaddreq, String patientemr) {
this.patientname = patientname;
this.patientage = patientage;
this.patientgender = patientgender;
this.patientinsurance = patientinsurance;
this.patientphone = patientphone;
this.patientdiagnosis = patientdiagnosis;
this.patientaddreq = patientaddreq;
this.patientemr = patientemr;
}
}
But I need the result like
{ { "patientname":"xyz"
"patientphone":"xyz"
"patientinsurance":"xyz"
"patientgender":"xyz"
"patientdiagnosis":"xyz"
"patientaddreq":"xyz" ... so on
}
}
you are returning List<String[]> and expect it to be a JSON list of your POJO?
change your method to return what is expected, like:
#Transactional
public List<PatientModel> fetchallpatients () {
Query q = entityManager.createNativeQuery("select * from patient p ");
List <PatientModel> patientList = q.getResultList();
System.out.println(patientList);
return patientList;
}
Related
I have the following response structure.
{
"URL": "",
"sites": [
{
"details": "",
"details2": "",
"details3": [
{
"moreDetails": "",
"moreDetails2": "",
}
]
},
{
"details": "",
"details2": "",
"details3": [
{
"moreDetails": "",
"moreDetails2": "",
}
]
}
]
}
This is accomplished by having multiple models.
SitesResponse
Sites
Details
MoreDetails
All of them have getter and setters and I just set up the response in the controller. Is there a way to move ALL of the response to a parent object without rewriting the hierarchy?
For an example, something like this:
{
"results": {
"URL": "",
"sites": [
{
"details": "",
"details2": "",
"details3": [
{
"moreDetails": "",
"moreDetails2": ""
}
]
},
{
"details": "",
"details2": "",
"details3": [
{
"moreDetails": "",
"moreDetails2": ""
}
]
}
]
}
}
you have to put them inside another object as below :
Result Model :
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"URL",
"sites"
})
public class Results {
#JsonProperty("URL")
private String uRL;
#JsonProperty("sites")
private List < Site > sites = null;
#JsonProperty("URL")
public String getURL() {
return uRL;
}
#JsonProperty("URL")
public void setURL(String uRL) {
this.uRL = uRL;
}
#JsonProperty("sites")
public List < Site > getSites() {
return sites;
}
#JsonProperty("sites")
public void setSites(List < Site > sites) {
this.sites = sites;
}
}
Site Model:
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"details",
"details2",
"details3"
})
public class Site {
#JsonProperty("details")
private String details;
#JsonProperty("details2")
private String details2;
#JsonProperty("details3")
private List < Details3 > details3 = null;
#JsonProperty("details")
public String getDetails() {
return details;
}
#JsonProperty("details")
public void setDetails(String details) {
this.details = details;
}
#JsonProperty("details2")
public String getDetails2() {
return details2;
}
#JsonProperty("details2")
public void setDetails2(String details2) {
this.details2 = details2;
}
#JsonProperty("details3")
public List < Details3 > getDetails3() {
return details3;
}
#JsonProperty("details3")
public void setDetails3(List < Details3 > details3) {
this.details3 = details3;
}
Details Model :
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"moreDetails",
"moreDetails2"
})
public class Details3 {
#JsonProperty("moreDetails")
private String moreDetails;
#JsonProperty("moreDetails2")
private String moreDetails2;
#JsonProperty("moreDetails")
public String getMoreDetails() {
return moreDetails;
}
#JsonProperty("moreDetails")
public void setMoreDetails(String moreDetails) {
this.moreDetails = moreDetails;
}
#JsonProperty("moreDetails2")
public String getMoreDetails2() {
return moreDetails2;
}
#JsonProperty("moreDetails2")
public void setMoreDetails2(String moreDetails2) {
this.moreDetails2 = moreDetails2;
}
}
Holder Model:
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"results"
})
public class Holder {
#JsonProperty("results")
private Results results;
#JsonProperty("results")
public Results getResults() {
return results;
}
#JsonProperty("results")
public void setResults(Results results) {
this.results = results;
}
}
then you can pass the Holder Model as a response
I stuck at this problem with Post Request, which gives me error 400 bad request, i have checked the JSON RequestBody via okHttpInterceptor by Retrofit and Json validated correctly. I don't know what's the problem with requestBody. it works with ModelAttribute though, but i want to pass data as requestBody.
This is my Spring Controller ->
#RequestMapping(value = "/updateProfile", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
#ResponseBody
public BasicResponse farmerUpdateProfile(#RequestBody UpdateFarmerRequest updateFarmerRequest, HttpServletRequest request) {
BasicResponse response = new BasicResponse();
// get authentication token and farmer ID from header
String requestAuthToken = (String) request.getHeader(MOBILE_AUTH);
String requestFarmerId = (String) request.getHeader(FARMER_ID);
// update farmer data, if id and AuthTokens are same...
// Validate Authentication Token
try {
if (!farmerMobileManager.validateAuthToken(requestFarmerId, requestAuthToken)) {
response.setErrorCode(ErrorCode.BAD_CREDENTIALS);
response.setResponse("Bad request error");
return response;
}
farmerMobileManager.updateFarmerRequest(updateFarmerRequest, response, requestFarmerId);
} catch (Exception ex) {
System.out.println(ex.getMessage());
response.setErrorCode(ErrorCode.INTERNAL_SERVER_ERROR);
response.setResponse("Error fetching prescriptions");
}
return response;
}
This is my UpdateFarmerRequestClass.
public class UpdateFarmerRequest {
#JsonProperty("farmer")
private Farmer farmer;
public void setFarmer(Farmer farmer) {
this.farmer = farmer;
}
public Farmer getFarmer() {
return farmer;
}
}
This is my Farmerclass ->
public class Farmer extends User {
private String farmerReferenceId;
private String cropId;
private String nomineeName;
private NomineeRelation nomineeRelation;
private String stateName;
private String mandalName;
private String villageName;
private String houseNumber;
private Boolean smartPhoneUser;
private SocialStatus socialStatus;
private EducationLevel educationLevel;
private String aadharNumber;
private String stateId;
private String districtId;
private String mandalId;
private String villageId;
private Boolean oneTimeDataEntered = false;
private ArrayList<CropData> cropData;
public String getHouseNumber() {
return houseNumber;
}
public String getCropId() {
return cropId;
}
public void setCropId(String cropId) {
this.cropId = cropId;
}
public List<CropData> getCropData() {
return cropData;
}
public void setCropData(List<CropData> cropData) {
List<CropData> newCropData = new ArrayList<>();
for (CropData cropDataItem : cropData) {
Boolean didFind = false;
for (CropData farmerCropData : this.cropData) {
// if it matched in db, update the record.
if (farmerCropData.getCrop().name().equals(cropDataItem.getCrop().name())) {
// update that you got the db record
didFind = true;
farmerCropData.setCropAcres(cropDataItem.getCropAcres());
farmerCropData.setCropName(cropDataItem.getCropName());
farmerCropData.setCropYield(cropDataItem.getCropYield());
}
}
if (!didFind) {
// if you didn't fnd the record, add to new crop data
newCropData.add(cropDataItem);
}
this.cropData.addAll(newCropData);
}
}
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public Farmer() {
super();
}
public String getNomineeName() {
return nomineeName;
}
public void setNomineeName(String nomineeName) {
this.nomineeName = nomineeName;
}
public NomineeRelation getNomineeRelation() {
return nomineeRelation;
}
public void setNomineeRelation(NomineeRelation nomineeRelation) {
this.nomineeRelation = nomineeRelation;
}
public String getMandalName() {
return mandalName;
}
public void setMandalName(String mandalName) {
this.mandalName = mandalName;
}
public String getVillageName() {
return villageName;
}
public void setVillageName(String villageName) {
this.villageName = villageName;
}
public Boolean getSmartPhoneUser() {
return smartPhoneUser;
}
public void setSmartPhoneUser(Boolean smartPhoneUser) {
this.smartPhoneUser = smartPhoneUser;
}
public SocialStatus getSocialStatus() {
return socialStatus;
}
public void setSocialStatus(SocialStatus socialStatus) {
this.socialStatus = socialStatus;
}
public EducationLevel getEducationLevel() {
return educationLevel;
}
public void setEducationLevel(EducationLevel educationLevel) {
this.educationLevel = educationLevel;
}
public String getAadharNumber() {
return aadharNumber;
}
public void setAadharNumber(String aadharNumber) {
this.aadharNumber = aadharNumber;
}
public String getFarmerReferenceId() {
return farmerReferenceId;
}
public void setFarmerReferenceId(String farmerReferenceId) {
this.farmerReferenceId = farmerReferenceId;
}
public String getStateId() {
return stateId;
}
public void setStateId(String stateId) {
this.stateId = stateId;
}
public String getDistrictId() {
return districtId;
}
public void setDistrictId(String districtId) {
this.districtId = districtId;
}
public String getMandalId() {
return mandalId;
}
public void setMandalId(String mandalId) {
this.mandalId = mandalId;
}
public String getVillageId() {
return villageId;
}
public void setVillageId(String villageId) {
this.villageId = villageId;
}
public Boolean getOneTimeDataEntered() {
return oneTimeDataEntered;
}
public void setOneTimeDataEntered(Boolean oneTimeDataEntered) {
this.oneTimeDataEntered = oneTimeDataEntered;
}
public List<String> collectErrors() {
List<String> errors = new ArrayList<String>();
if (StringUtils.isEmpty(this.villageId)) {
errors.add("villageId");
}
// if (StringUtils.isEmpty(this.nomineeName)) {
// errors.add("nomineeName");
// }
if (StringUtils.isEmpty(this.getFirstName())) {
errors.add("firstName");
}
if (StringUtils.isEmpty(this.getPhoneNumber()) || !CommonUtils.validatePhoneNumber(this.getPhoneNumber())) {
errors.add("phoneNumber");
}
return errors;
}
public List<String> collectSignUpErrors() {
List<String> errors = new ArrayList<String>();
if (StringUtils.isEmpty(this.villageId)) {
errors.add("villageId");
}
if (StringUtils.isEmpty(this.getFirstName())) {
errors.add("firstName");
}
if (StringUtils.isEmpty(this.getPhoneNumber()) || !CommonUtils.validatePhoneNumber(this.getPhoneNumber())) {
errors.add("phoneNumber");
}
return errors;
}
public static class Constants extends User.Constants {
public static final String FARMER_REFERENCE_ID = "farmerReferenceId";
public static final String AADHAR_NUMBER = "aadharNumber";
public static final String MANDAL_ID = "mandalId";
public static final String VILLAGE_ID = "villageId";
public static final String FARMER_ID = "_id";
}
}
this is my RequestBody that i am sending in POSTMAN.
RequestBody ->
{
"farmer": {
"city": "",
"mandalName": "",
"stateName": "",
"villageName": "",
"countryCode": "+",
"cropData": [{
"crop": "RICE",
"cropAcres": 1.0,
"cropName": "RICE",
"cropYield": 2.0
}, {
"crop": "PADDY",
"cropAcres": 4.0,
"cropName": "PADDY",
"cropYield": 5.0
}
],
"cropId": "",
"districtId": "",
"farmerReferenceId": "",
"firstName": "",
"houseNumber": "",
"id": "",
"mandalId": "",
"phoneNumber": "",
"stateId": "",
"villageId": ""
}
}
The Data are not empty, but i am purposely not filling it for privacy purpose.
I have solved my problem, it was naming convention problem, as i was passing cropData as "cropData", while at server Side it was "CropData."
Could anyone tell me what am I doing wrong while printing the JSON using Jackson. Here's my controller code :
#RequestMapping(value="/get_employee_details", method=RequestMethod.GET)
public String updateemployee
(
#RequestParam(value="emp_id", defaultValue="0") Integer emp_id,
#RequestParam(value="name", defaultValue="") String name
)
{
String responseJSON = null;
boolean getStatus = true;
try {
EmployeeDao employeeDao = (EmployeeDao)context.getBean("employeeDao");
Employee employee = null;
List<Employee> empList = employeeDao.findByEmployeeId(emp_id);
if ((empList != null) && (!empList.isEmpty())) {
List<String> empStatus = new ArrayList<String>();
for(Employee emp : empList){
empStatus.add(emp.addJoinString());
responseJSON = GenericOrmStatusView.OrmResponseToJsonString(true, 1,empStatus, true);
}
}
}
return responseJSON;
}
I have the following method defined in my Employee class :
public String addJoinString() {
return String.format("ID: %d",Name: %s," ,this.EmployeeId,this.name);
}
Since I am running a for loop in the code here and sending the list empStatus to the OrmResponseToJsonString method :
for(Employee emp : empList){
empStatus.add(emp.addJoinString());
responseJSON = GenericOrmStatusView.OrmResponseToJsonString(true, 1,empStatus, true);
I am getting the following JSON response :
{
"status" : "SUCCESS",
"employeeStatus" : [ "ID: 81, Name: Jack", "ID: 83, Name: Anthony", "ID: 88, Name: Stephanie", "ID: 25, Name: Kelly", "ID: 02, Name: Jessica" ]
}
However, I would like to be it in the following format:
{
"status" : "SUCCESS",
"message": " "
},
"employeeStatus":[{
"ID":81,
"Name":"Jack"
},
{
"ID":88,
"Name":"Anthony"
},
and so on and so forth ....
]
For Reference:
My OrmResponseToJsonString method is defined as follows inside GenericOrmStatusView class
public class GenericOrmStatusView extends Views
{
public static String OrmResponseToJsonString(boolean success, List<String> eStatus,boolean pretty)
{
PrintemployeeStatusIDAndStatus statusMsg = WebServiceUtils.printNameAndID(success, eStatus);
String genericOrmStatusJsonString = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, pretty);
genericOrmStatusJsonString = objectMapper.writerWithView(Views.Normal.class).writeValueAsString(statusMsg);
//genericOrmStatusJsonString = objectMapper.writerWithView(Views.Normal.class).writeValueAsString(eStatus);
} catch(Exception e) {
e.printStackTrace();
}
return genericOrmStatusJsonString;
}
}
And my printNameAndID method is defined as follows inside WebServiceUtils class :
public class WebServiceUtils
{
public static PrintNameAndID printNameAndID(boolean success, List<String> eStatus)
{
PrintNameAndID statusMsgAndRegID = new PrintNameAndID();
if (success) {
statusMsgAndRegID.setStatus("SUCCESS");
statusMsgAndRegID.setemployeeStatus(eStatus);
} else {
statusMsgAndRegID.setStatus("ERROR");
//statusMsgAndRegID.setemployeeStatus("");
}
return statusMsgAndRegID;
}
}
The easiest way to get desired JSON output, is to create an object model representing the data, e.g.
public class MyJSON {
private MyStatus status;
private List<EmployeeStatus> employeeStatus = new ArrayList<>();
public MyJSON(String status, String message) {
this.status = new MyStatus(status, message);
}
public void addEmployeeStatus(int id, String name) {
this.employeeStatus.add(new EmployeeStatus(id, name));
}
public MyStatus getStatus() {
return this.status;
}
public List<EmployeeStatus> getEmployeeStatus() {
return this.employeeStatus;
}
}
public class MyStatus {
private String status;
private String message;
public MyStatus(String status, String message) {
this.status = status;
this.message = message;
}
public String getStatus() {
return this.status;
}
public String getMessage() {
return this.message;
}
}
public class EmployeeStatus {
private int id;
private String name;
public EmployeeStatus(int id, String name) {
this.id = id;
this.name = name;
}
#JsonProperty("ID")
public int getId() {
return this.id;
}
#JsonProperty("Name")
public String getName() {
return this.name;
}
}
You can then create JSON text like this:
MyJSON myJSON = new MyJSON("SUCCESS", " ");
myJSON.addEmployeeStatus(81, "Jack");
myJSON.addEmployeeStatus(88, "Anthony");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
String json = objectMapper.writeValueAsString(myJSON);
System.out.println(json);
Output
{
"status" : {
"status" : "SUCCESS",
"message" : " "
},
"employeeStatus" : [ {
"ID" : 81,
"Name" : "Jack"
}, {
"ID" : 88,
"Name" : "Anthony"
} ]
}
As mentioned by chrylis in a comment:
As a note, you can normally let Spring do this automatically and just return empList from your controller method.
Which for the above code would mean something like this:
#GetMapping(path="/foo", produces="application/json")
public MyJSON foo() {
MyJSON myJSON = new MyJSON("SUCCESS", " ");
myJSON.addEmployeeStatus(81, "Jack");
myJSON.addEmployeeStatus(88, "Anthony");
return myJSON;
}
I have json data :
[
{
"RouteNo": "004",
"RouteName": "POWELL/DOWNTOWN/UBC",
"Direction": "WEST",
"Schedules": [
{
"Destination": "UBC",
"ExpectedCountdown": -4,
},
{
"Destination": "Downtown",
"ExpectedCountdown": -6,
}
]
},
{
"RouteNo": "006",
"RouteName": "Grange str",
"Direction": "South",
"Schedules": [
{
"Destination": "Victoria",
"ExpectedCountdown": -9,
},
{
"Destination": "College station",
"ExpectedCountdown": -15,
}
]
}
]
And I have my model Route.java:
public class Route {
public String getRouteNo() {
return RouteNo;
}
public void setRouteNo(String routeNo) {
RouteNo = routeNo;
}
public String getRouteName() {
return RouteName;
}
public void setRouteName(String routeName) {
RouteName = routeName;
}
public Route(String routeNo, String routeName) {
RouteNo = routeNo;
RouteName = routeName;
}
private String RouteNo;
private String RouteName;
}
My question is how should I insert Schedules object you can see in json data into Route model? I am confused in terms of (as far as I understood) it is an object containing an array and I am not sure how to represent it in this case. And how actually get the data from it in retrofit call? I need to get each destination for each route.
Update Route to be:
public class Route {
public String getRouteNo() {
return RouteNo;
}
public void setRouteNo(String routeNo) {
RouteNo = routeNo;
}
public String getRouteName() {
return RouteName;
}
public void setRouteName(String routeName) {
RouteName = routeName;
}
public Route(String routeNo, String routeName) {
RouteNo = routeNo;
RouteName = routeName;
}
private String RouteNo;
private String RouteName;
private List<Schedule> schedules; // add mutators with #JsonProperty annotation
}
Then create the Schedule class as described by the above JSON
I have restful webservice returning list of pojo objects which is not generating correct json format.
The following is the code which is not return json object
#RequestMapping("/getThisWeekPlan")
public List<ShiftPlannerView> getThisWeekPlan() {
return getShiftPlanRepo.fetchThisWeekShiftPlan();
}
My POJO where setting the result from JPA with hibernate using namedquery
public class ShiftPlannerView {
public ShiftPlannerView() {
}
private Date shiftPlannerDate;
private String resourceName;
private String shiftName;
public ShiftPlannerView(Date shiftPlannerDate, String resourceName, String shiftName) {
super();
this.shiftPlannerDate = shiftPlannerDate;
this.resourceName = resourceName;
this.shiftName = shiftName;
}
public Date getShiftPlannerDate() {
return shiftPlannerDate;
}
public void setShiftPlannerDate(Date shiftPlannerDate) {
this.shiftPlannerDate = shiftPlannerDate;
}
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
public String getShiftName() {
return shiftName;
}
public void setShiftName(String shiftName) {
this.shiftName = shiftName;
}
#Override
public String toString() {
return "ShiftPlannerView [shiftPlannerDate=" + shiftPlannerDate + ", resourceName=" + resourceName
+ ", shiftName=" + shiftName + "]";
}
}
DB call
#Repository
public class GetShiftPlanRepoImpl implements GetShiftPlanRepo{
#PersistenceContext
EntityManager em;
#Override
public List<ShiftPlannerView> fetchThisWeekShiftPlan() {
List<ShiftPlannerView> result= em.createNamedQuery("fetchByShiftPlannerThisWeek")
.getResultList();
return result;
}
}
The following is the response:
[
[
"2018-04-16",
"Elias",
"I"
],
[
"2018-04-16",
"Sithik",
"II"
],
[
"2018-04-17",
"Vikram Boya",
"I"
],
[
The following code changes brought me expected response
#Override
public List<ShiftPlannerView> fetchThisWeekShiftPlan() {
List<ShiftPlannerView> listOfShiftPlannerView=new ArrayList<>();
try {
Query q= em.createNativeQuery(ShiftPlannerConstants.THISWEEKSHIFTPLANQUERY);
List<Object[]> result=q.getResultList();
for(Object[] row : result){
ShiftPlannerView emp = new ShiftPlannerView();
Date workingDays = sdf.parse(row[0].toString());
emp.setShiftPlannerDate(workingDays);
emp.setResourceName(row[1].toString());
emp.setShiftName(row[2].toString());
listOfShiftPlannerView.add(emp);
}
}catch (Exception e) {
e.printStackTrace();
}
Thanks to JB!