Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

471
Visualizações
Spring Boot - Unable to De-serialize JSON Object Sent by Fetch

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.HeartRateEntry from Array value (token JsonToken.START_ARRAY); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type com.c3.healthapp.model.HeartRateEntry from Array value (token JsonToken.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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda