javaspringpostgresqlpostman

HttpMessageNotReadableException errors on my Spring Framework


I want to send an object to my database, with spring framework. Here is my code in the controller :

@PostMapping("/createBarangByJson")
    public ResponseEntity<?> createBarangByJson(@RequestBody RequestUser body)
    {
        Integer cDet = crudService.simpleCreateByJson(body);
        return ResponseEntity.ok(cDet);
    }
}

I already make setter getter for request class, and here is my code in DaoImpl:

@Override
public Integer simpleCreateByJson(RequestUser reqUser)
{
    String sql = "INSERT INTO public.jualbeli(nama_barang, kuantitas, harga, tanggal, created_by) VALUES (?,?,?,?,?)";
    Integer result = jdbcTemplate.update(sql, reqUser.getNama_barang(), Integer.parseInt(reqUser.getKuantitas()), Integer.parseInt(reqUser.getHarga()), reqUser.getTanggal(), reqUser.getCreated_by());
    return result;
}

But when I send this data:

[
    {
        "nama_barang": "buku",
        "kuantitas": "17",
        "harga": "500000",
        "tanggal": "2020-08-01",
        "created_by": "adit"
    }
]

The error said:

"timestamp": 1615207817069,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException"

Anybody knows what's wrong ?


Solution

  • You are sending a JSON array:

    [{
        "nama_barang": "buku",
        "kuantitas": "17",
        "harga": "500000",
        "tanggal": "2020-08-01",
        "created_by": "adit"
    }]
    

    You need to send

    {
        "nama_barang": "buku",
        "kuantitas": "17",
        "harga": "500000",
        "tanggal": "2020-08-01",
        "created_by": "adit"
    }
    

    Also you should require

    @PostMapping(path="/createBarangByJson", consumes="application/json") 
    

    instead of

    @PostMapping("/createBarangByJson")