JSON array within an object is not being parsed - json

I'm using hibernate, spring, and fasterxml/Jackson to create JSON based rest services.
I'm sending in the following JSON:
{
"allParts" : true,
"aogLocation" : "LAS",
"companyId" : "20",
"controlNo" : "1",
"controlSeq" : "1234",
"dateNeeded" : "2020-02-24",
"timeNeeded" : "800",
"employeeId" : "bob",
"inventoryLocation" : "LAS",
"requestType" : "STOCK",
"shippingAddress": "123 e. st. Las Vegas, NV 12345",
"tailNo" : "abc",
"partsRequestLines" : [
{
"location": "LAS",
"lineNote" : "I need this part really bad",
"requestedPartDescription" : "it makes a plane go.",
"requestedPartNumber" : "abc-123",
"requestedQuantity" : 10
}
]
}
To be parsed into the following classes:
#Getter
#Setter
public class PartsRequestDto extends AbstractDto {
private Boolean allParts;
private String aogLocation;
private Date chgdate;
private Integer chgpage;
private String chgprog;
private String chgtype;
private String chguser;
private String companyId;
private String controlNo;
private Integer controlSeq;
private Date dateNeeded;
private String employeeId;
private String inventoryLocation;
private Date requestDate;
private Integer requestId;
private String requestType;
private String shippingAddress;
private Integer status;
private Timestamp sysEnd;
private Timestamp sysStart;
private String tailNo;
private String timeNeeded;
private Timestamp transStart;
private List<PartsRequestLineDto> partsRequestLines;
public PartsRequestDto() {
}
public PartsRequestDto(Boolean allParts, String aogLocation, Date chgdate, Integer chgpage, String chgprog,
String chgtype, String chguser, String companyId, String controlNo, Integer controlSeq,
Date dateNeeded, String employeeId, String inventoryLocation, Date requestDate, Integer requestId,
String requestType, String shippingAddress, Integer status, Timestamp sysEnd, Timestamp sysStart,
String tailNo, String timeNeeded, Timestamp transStart) {
this.allParts = allParts;
this.aogLocation = aogLocation;
this.chgdate = chgdate;
this.chgpage = chgpage;
this.chgprog = chgprog;
this.chgtype = chgtype;
this.chguser = chguser;
this.companyId = companyId;
this.controlNo = controlNo;
this.controlSeq = controlSeq;
this.dateNeeded = dateNeeded;
this.employeeId = employeeId;
this.inventoryLocation = inventoryLocation;
this.requestDate = requestDate;
this.requestId = requestId;
this.requestType = requestType;
this.shippingAddress = shippingAddress;
this.status = status;
this.sysEnd = sysEnd;
this.sysStart = sysStart;
this.tailNo = tailNo;
this.timeNeeded = timeNeeded;
this.transStart = transStart;
}
}
#Getter
#Setter
#AllArgsConstructor
public class PartsRequestLineDto implements Serializable {
private Integer id;
private Integer reqId;
private String location;
private String requestType;
private Date etaTimestamp;
private Date neededTimestamp;
private Date requestedTimestamp;
private Integer status;
private String tailNumber;
private String lineNote;
private String packingListId;
private String requestedPartDescription;
private String requestedPartNumber;
private Integer requestedQuantity;
public PartsRequestLineDto() {
}
}
I send that JSON into the following REST API:
#RequestMapping(value = "/create", method = RequestMethod.POST)
public PartsRequestDto createPartsRequest(PartsRequestDto partsRequestDto) throws Exception {
PartsRequest partsRequest = partsRequestService.constructPartsRequestFromDto(partsRequestDto);
PartsRequestDto response = partsRequestService.createPartsRequest(partsRequest);
return response;
}
It parses the PartsRequest object just fine, but sets the partsRequestLines list to null. Can someone tell me how to get Jackson/REST to parse the sub-object list correctly?

I figured it out. My method signature on the API was missing a #RequestBody annotation.

Related

Is there way to resolve this i was not able to get correct JSON response from my model class below provided the model class and response

Model Class variables:
#JsonProperty("companyId")
private String companyId;
#JsonProperty("companyName")
private String companyName;
#JsonProperty("skuId")
private String skuId;
#JsonProperty("skuName")
private String skuName;
#JsonProperty("unitMrp")
private Integer unitMrp;
#JsonProperty("unitPerSU")
private Integer unitPerSU;
#JsonProperty("balance")
private Integer balance;
#JsonProperty("SUnitC")
private BigDecimal SUnitC;
#JsonProperty("SUPercase")
private Integer SUPercase;
Response:
{
"SUPercase": 0,
"SUnitC": 0,
"balance": 0,
"companyId": "string",
"companyName": "string",
"skuId": "string",
"skuName": "string",
**"sunitC": 0,
"supercase": 0,**
"unitMrp": 0,
"unitPerSU": 0
}
you need to set visibility on class level (POJO)
#JsonAutoDetect(fieldVisibility=JsonAutoDetect.Visibility.ANY,getterVisibility=JsonAutoDetect.Visibility.NONE, setterVisibility=JsonAutoDetect.Visibility.NONE, creatorVisibility=JsonAutoDetect.Visibility.NONE)
#JsonIgnoreProperties(ignoreUnknown = true)
public Class Model{
#JsonProperty("companyId")
private String companyId;
#JsonProperty("companyName")
private String companyName;
#JsonProperty("skuId")
private String skuId;
#JsonProperty("skuName")
private String skuName;
#JsonProperty("unitMrp")
private Integer unitMrp;
#JsonProperty("unitPerSU")
private Integer unitPerSU;
#JsonProperty("balance")
private Integer balance;
#JsonProperty("SUnitC")
private BigDecimal SUnitC;
#JsonProperty("SUPercase")
private Integer SUPercase;
//Setter
//getter
}

Spring Boot Maven and MySQL Error Handling

I have the following Spring Boot MySQL query:
visitorrepository.save(newvisitor)
Upon execution of this MySQL query, I want to return a success JSON or failure JSON in the following format:
Success State:
{
"success": true,
"message": "Some Helpful Message",
"data": { } //This would be the newvisitor JSON that includes the primary key (id)
}
Failure State:
{
"success": false,
"message": "Some Helpful Message",
"error_code": "404", // This should be whatever error number was returned
"data": { } //This would be the newvisitor JSON that does not include the primary key (id)
}
In angular the response is captured as follows
this.http.post('http://localhost:8080/v1/api/post', this.visitor.value).toPromise().then((response:any) => {
console.log(response);
})
post.java
#CrossOrigin(origins = "http://localhost:4200")
#RestController
public class post {
#Autowired
visitorrepository visitorrepository;
#PostMapping("/v1/api/post")
public void insert(#Valid #RequestBody newvisitor newvisitor) {
try {
visitorrepository.save(newvisitor);
return // Success State JSON
} catch () {
return // Error State JSON
}
}
}
newvisitor.java
#Getter
#Setter
#Entity
#Table(name = "visitors")
public class newvisitor {
#Id
#GeneratedValue
private Long id;
#Size(min=1, max=250)
#NotBlank
private String firstname;
#NotBlank
private String lastname;
#NotBlank
private String month;
#NotBlank
private String day;
#NotBlank
private String year;
#NotBlank
private String socialsecuritynumber;
#NotBlank
private String street1;
private String street2;
#NotBlank
private String city;
#NotBlank
private String state;
#NotBlank
private String zip;
#NotBlank
private String phone;
#Email
#NotBlank
private String email;
public newvisitor(){
super();
}
public newvisitor(String firstname, String lastname, String month, String day, String year, String socialsecuritynumber, String street1, String street2, String city, String state, String zip, String phone, String email) {
super();
this.firstname = firstname;
this.lastname = lastname;
this.month = month;
this.day = day;
this.year = year;
this.socialsecuritynumber = socialsecuritynumber;
this.street1 = street1;
this.street2 = street2;
this.city = city;
this.state = state;
this.zip = zip;
this.phone = phone;
this.email = email;
}
}
visitorrepository.java
#Repository
public interface visitorrepository extends CrudRepository<newvisitor, Long> {
}
The thought is to catch everything from MySQL database not connecting, to invalid data entry, to duplicate records, bascially anything that prevented the initial query visitorrepository.save(newvisitor) from working, and return this to angular as a JSON. I feel like ResponseEntity or RestControllerAdvice might be the answer, just not sure best way to implement if this is accurate.
You already have the answer.
I feel like ResponseEntity or RestControllerAdvice might be the answer
You only create a dto response with your format. then put it in ResponseEntity in case error or not.

post and put method doesn't work for me "error": "Unsupported Media Type"

i have this error message when i try post and put method on patients but get method work for me.
"error": "Unsupported Media Type",
"message": "Content type 'application/json;charset=UTF-8' not supported",
i guess the problem with #JsonBackReference. when i delete #JsonBackReference i have this error message when i try get method : There was an error parsing JSON data
Unexpected end of JSON input
code here
class patients
#Entity
public class Patient {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id_pat;
private Integer cin_pat;
private String fname_pat;
private String lname_pat;
private String sexe_pat;
#Temporal(javax.persistence.TemporalType.DATE)
private Date date_naissance_pat;
private String ville_pat;
private String poid_pat;
private String mail_pat;
private Integer num_tel_pat;
private String adress_pat;
private String remarque_pat;
private String malade_pat;
private String medicament_pat;
#Temporal(javax.persistence.TemporalType.DATE)
private Date der_soin_pat;
private String mot_de_passe_pat;
#OneToMany(cascade = CascadeType.ALL, mappedBy="patient", orphanRemoval = true)
private List<Rdv> Rdvs;
public Patient(){
}
public Patient(Integer id_pat, Integer cin_pat, String fname_pat, String lname_pat, String sexe_pat, Date date_naissance_pat, String ville_pat, String poid_pat, String mail_pat, Integer num_tel_pat, String adress_pat, String remarque_pat, String malade_pat, String medicament_pat, Date der_soin_pat, String mot_de_passe_pat) {
this.id_pat = id_pat;
this.cin_pat = cin_pat;
this.fname_pat = fname_pat;
this.lname_pat = lname_pat;
this.sexe_pat = sexe_pat;
this.date_naissance_pat = date_naissance_pat;
this.ville_pat = ville_pat;
this.poid_pat = poid_pat;
this.mail_pat = mail_pat;
this.num_tel_pat = num_tel_pat;
this.adress_pat = adress_pat;
this.remarque_pat = remarque_pat;
this.malade_pat = malade_pat;
this.medicament_pat = medicament_pat;
this.der_soin_pat = der_soin_pat;
this.mot_de_passe_pat = mot_de_passe_pat;
}
// Getters & Setters
}
patient controller
#RestController
public class PatientController {
#Autowired
PatientService patientService;
#GetMapping("/patients")
private List<Patient> getAllPatients() {
return patientService.getAllPatients();
}
#GetMapping("/patients/{id_pat}")
private Patient getPatient(#PathVariable("id_pat") Integer id_pat){
return patientService.getPatientById(id_pat) ;
}
#PostMapping("/patients")
public void addPatient(#RequestBody Patient patient){
patientService.addPatient(patient);
}
#PutMapping("/patients/{id_pat}")
public void upatePatient (#RequestBody Patient patient, #PathVariable String id_pat){
patientService.updatePatient(id_pat, patient);
}
#DeleteMapping("/patients/{id_pat}")
private void deletePatient(#PathVariable("id_pat") Integer id_pat){
patientService.delete(id_pat);
}
}
patient sevice
#Service
public class PatientService {
#Autowired
private PatientRepository patientRepository;
public List<Patient> getAllPatients() {
List<Patient> patients = new ArrayList<Patient>();
patientRepository.findAll().forEach(patient-> patients.add(patient));
return patients;
}
public Patient getPatientById(Integer id_pat){
return patientRepository.findById(id_pat).get();
}
public void addPatient(Patient patient) {
patientRepository.save(patient);
}
public void updatePatient(String id_pat, Patient patient){
patientRepository.save(patient);
}
public void delete(Integer id_pat){
patientRepository.deleteById(id_pat);
}
}
rdv entity
#Entity
public class Rdv {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id_rdv;
#Temporal(javax.persistence.TemporalType.DATE)
private Date date_rdv;
private Time time_rdv;
#JsonBackReference
#ManyToOne( fetch = FetchType.LAZY)
#JoinColumn(name = "id")
private Medecin medecin;
#JsonBackReference
#ManyToOne( fetch = FetchType.LAZY)
#JoinColumn(name = "id_pat")
private Patient patient;
public Rdv() {}
public Rdv(Integer id_rdv, Date date_rdv, Time time_rdv, Integer id, Integer id_pat) {
this.id_rdv = id_rdv;
this.date_rdv = date_rdv;
this.time_rdv = time_rdv;
this.medecin = new Medecin(id, "", "", "", null, "", "", "");
this.patient = new Patient(id_pat, null, "", "", "", null, "", null, "", null, "", "", "", "", null, "");
}
// Getters & Setters
}
patient repository
public interface PatientRepository extends JpaRepository<Patient, Integer> {
}
rdv repository
public interface SecretaireRepository extends JpaRepository<Secretaire, Integer>{
public List<Secretaire> findByMedecinId(Integer id);
}

data is posting as anonymous user in the data base when posting from postman

This is my entity class where it is having createdBy and lastModifiedBy fields. When ever I'm posting the data from postman for the fields 'createdBy' and 'lastModifiedBy' the columnn in the database is saving as anynomous user instead of the name which is posting from the postman
#Slf4j
#Getter
#Setter
#MappedSuperclass
#EntityListeners(AuditingEntityListener.class)
public abstract class AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
//#CreatedBy
#Column(name = "created_by", nullable = false, length = 50, updatable = false)
//#JsonIgnore
private String createdBy;
#CreatedDate
#Column(name = "created_date", updatable = false)
#JsonIgnore
private Instant createdDate = Instant.now();
//#LastModifiedBy
#Column(name = "last_modified_by", length = 50)
//#JsonIgnore
private String lastModifiedBy;
#LastModifiedDate
#Column(name = "last_modified_date")
#JsonIgnore
private Instant lastModifiedDate = Instant.now();
From the UserRequestDTO it is posting the request which is given below
UserRequestDTO.class
#Data
public class UserRequestDTO {
#NotBlank
#ApiModelProperty(required = true, name = "UserName must be between 3 and 255 characters long", position = 0)
#Size(min = 3, max = 255)
private String userName;
private NameDTO name;
#NotBlank
#ApiModelProperty(required = true, name = "displayName must be between 3 and 100 characters long")
#Size(min = 3, max = 100)
private String displayName;
#ApiModelProperty(example = "1")
private Long organizationId;
#Lob
private String photo;
#ApiModelProperty(example = "India")
private String country;
#ApiModelProperty(example = "bhargav")
private String createdBy;
#ApiModelProperty(example = "bhargav")
private String lastModifiedBy;
}
}
This is the data which I'm trying to post from the post man.
{
"userName": "jaya",
"displayName": "jay",
"country":"USA",
"createdBy":"bhargav",
"lastModifiedBy":"jaya krishna",
"phoneNumber":"9876543210",
"email":"jaya#abc.com",
"startDate":"2019-12-08",
"endDate":"2020-01-08"
}
But the createdBy column and the lastModified column is saving as the anynomous user instead of the name which is posting from the POSTMAN. datatype of both the columns is varchar.
Can you please share the User Entity witch you are trying to persist in the Database, also if you can share how you are mapping DTO with Entity Object.

convert json String to array java object by Gson

I never understand that how can I use gson.
this is my json string that is fetched from my web service:
{
"GetHistoricalNotificationsInTopicByFilterResult":[
{
"BusinessCode":"10-1-75-16-1-3-0",
"CreationDateTime":"\/Date(1502550561602)\/",
"DeviceId":"8998432005",
"Distributions":null,
"EventData":[ ],
"EventId":"com.test.revisit.events",
"EventTitle":"sending",
"Id":"69dbc367-09ws-bf3c-9re8-5c6b35ecbrtg",
"ProcessId":"4ebb6271-bf3c-9re8-a148-5c6b35ec458",
"SystemId":"com.safarayaneh.revisit",
"SystemTitle":"seeing",
"UserFullName":"jack",
"UserId":"69dbc367-32f3-4e94-bf3c-5c6b35ec3456",
"WKT":"POLYGON ((59.0 36.0, 59.01 36.01, ...))",
"WorkItemId":2354365
},{
....
}
and this is my contract class:
public class SaveNotify implements Parcelable {
private long id;
private String NotificationID;
private String MessageID;
private String CreationDateTime;
private String DeviceId;
private String UserId;
private String UserFullName;
private String SystemId;
private String SystemTitle;
private String EventId;
private String EventTitle;
private String EventData;
private String BusinessCode;
private String ProcessId;
private String WorkItemId;
private String WKT;
private String Distributions;
private String Address;
private String SaveDate;
private String Status;
private String DistributionId;
private String SchedulerCreationDateTime;
private String ExpirationDateTime;
how can I convert json string that i receive from my webservice to pojo class as array list? I want to put this list to my recycler view adapter for showing this info as a list.
What you need to create is an object that gets the field GetHistoricalNotificationsInTopicByFilterResult
public class MainObject implements Parceable{
List<SaveNotify > GetHistoricalNotificationsInTopicByFilterResult;
}
And then, with Gson parce you JSON to The MainObject
Gson gson = new Gson();
MainObject mainObject = gson.fromJson(jsonString, MainObject.class);