I'm trying to send a JSON object from the front-end js to Spring Boot. I keep getting the following error in Spring Boot
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type
com.c3.healthapp.model.HeartRateEntryfrom Array value (tokenJsonToken.START_ARRAY); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of typecom.c3.healthapp.model.HeartRateEntryfrom Array value (tokenJsonToken.START_ARRAY)<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]]
and a status 400 on the client side.
The Javascript function being used to send is
function saveEntryToDB(entry){
fetch("/customer/heartrate/save", {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(entry)
}).then(res => {
console.log("User saved. response:", res);
});
}
The object being sent
{
entryHeartRate: 55,
dateOfEntry: Tue Mar 01 2022 00:00:00 GMT+0000 (Greenwich Mean Time)
}
Spring boot controller method
@PostMapping("/heartrate/save")
public ResponseEntity<String> saveHeartRate(@RequestBody HeartRateEntry heartRateEntry) {
String username = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
Customer customer = customerService.getCustomer(username);
customer.getHeartRateEntries().add(heartRateEntry);
customerService.saveCustomer(customer);
URI uri = URI.create(ServletUriComponentsBuilder.fromCurrentContextPath().path("/heartrate/save").toUriString());
return ResponseEntity.created(uri).body("Saved!");
}
and HeartRateEntry class
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class HeartRateEntry {
@Id
@GeneratedValue(strategy = IDENTITY)
private Long entryId;
private int entryHeartRate;
private Date dateOfEntry;
@Override
public String toString() {
return "Entry Id: " + entryId + " Entry Heart Rate: " + entryHeartRate + " Date Of Entry : " + dateOfEntry;
}
}
So far, I've been able to submit other entities from HTML forms and get values (including an array of heart rate entries) returned from Spring Boot with no issues.
I have tried formatting the date as dd/mm/yy and adding the annotation '@JsonFormat(pattern="dd/mm/yyyy")' to the dateOfEntry attribute in the HeartRateEntry class, in case it was somehow an issue with date parsing, but this doesn't seem to make a difference.
I have also tried adding an id attribute to the JSON object prior to sending. This doesn't seem to make a difference either.
I had to create a null JS object and add the values to that before submission. I believe it's to do with the javascript object prototype being stored within the created object.
let nullEntry = Object.create(null);
nullEntry.entryHeartRate = entry.entryHeartRate;
nullEntry.entryHeartRate = entry.dateOfEntry;
saveEntryToDB(nullEntry);