简体   繁体   中英

json parse error post data spring boot mysql

I have this problem in the back end when I post a data form from angular please someone help me I trie to solve this problem by object mapper but I don't understand well how can I do it correctly the error is:

  • Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of entity.Group (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{ "idGrp": 2, "nomGroup": "intr.net" }'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of entity.Group (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{ "idGrp": 2, "nomGroup": "intr.net" }') at [Source: (PushbackInputStream); line: 1, column: 236] (through reference chain: entity.Employe["group"])]*

this is my class Group

package entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="groups")
public class Group implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long idGrp;
    
    private String NomGroup;
    
    public Group()
    {
        
    }

    public Group(Long id, String nomGroup) {
        super();
        this.idGrp = id;
        NomGroup = nomGroup;
    }


}

Im trying to post a data of employee which contain the data of entity group class employee

package entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.GenericGenerator;

@Entity
public class Employe  implements Serializable {
     @Id
     @GeneratedValue(strategy = GenerationType.AUTO, generator = "myid")
     @GenericGenerator(name = "myid", strategy = "entity.MyGenerator")
     private Integer matricule;

    private String  nom;
    
    private String   prenom ;

     private String  nom_ar;
    
     private String prenom_ar;

     
     private int age;
    
     private String description;

     private String email;

     private int codeP;

     private int numTele;

     private String adresse;

     private String  ville;
     @JoinColumn(name="idGrp")
     @ManyToOne(cascade = {CascadeType.ALL})     
    Group group;
     
     
    
    public Employe(Integer matricule, String nom, String prenom, String nom_ar, String prenom_ar, int age,
            String description, String email, int codeP, int numTele, String adresse, String ville, Group group) {
        super();
        this.matricule = matricule;
        this.nom = nom;
        this.prenom = prenom;
        this.nom_ar = nom_ar;
        this.prenom_ar = prenom_ar;
        this.age = age;
        this.description = description;
        this.email = email;
        this.codeP = codeP;
        this.numTele = numTele;
        this.adresse = adresse;
        this.ville = ville;
    
    }
    public Employe(Integer matricule, String nom, String prenom, String nom_ar, String prenom_ar, int age,
            String description, String email, int codeP, int numTele, String adresse, String ville) {
        
        this.matricule = matricule;
        this.nom = nom;
        this.prenom = prenom;
        this.nom_ar = nom_ar;
        this.prenom_ar = prenom_ar;
        this.age = age;
        this.description = description;
        this.email = email;
        this.codeP = codeP;
        this.numTele = numTele;
        this.adresse = adresse;
        this.ville = ville;
    }


}

controller

 @CrossOrigin(origins = "http://localhost:4200")
    
    @PostMapping("addEmp")
    public ResponseEntity<Employe> addEmp(@RequestBody Employe ep) throws JsonProcessingException
    {
        Employe p=this.servEmp.addEmp(ep);
    
    return new ResponseEntity<>(p, HttpStatus.CREATED);
        }

please help me how can I convert the json data to object I spend now two days In this error

I try to use commandRunner 
    @Bean
       public CommandLineRunner run(ServiceEmp ServiceEmp) {
        
        return args->{
            
            Employe e=new Employe(0,"","","","",0,"","",0,0,"","");
            ObjectMapper objectMapper=new ObjectMapper();
            TypeReference<Employe> TypeReference =new TypeReference<Employe>() {};
            InputStream InputStream=TypeReference.class.getResourceAsStream(objectMapper.writeValueAsString(ServiceEmp.addEmp(e)));
            try {
                    e=objectMapper.readValue(InputStream,TypeReference);
            ServiceEmp.addEmp(e);
            System.out.print("saved");
            
            }
            catch(IOException a)
            {
                System.out.print("not saved"+a.getMessage());
                
            }

output:

**Employe [nom=, prenom=, nom_ar=, prenom_ar=, matricule=0, age=0, description=, email=, codeP=0, numTele=0, adresse=, ville=]
[2m2021-09-25 20:40:39.966[0;39m [32m INFO[0;39m [35m10044[0;39m [2m---[0;39m [2m[           main][0;39m [36mConditionEvaluationReportLoggingListener[0;39m [2m:[0;39m 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
[2m2021-09-25 20:40:39.992[0;39m [31mERROR[0;39m [35m10044[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.s.boot.SpringApplication              [0;39m [2m:[0;39m Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:794) ~[spring-boot-2.5.4.jar:2.5.4]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:775) ~[spring-boot-2.5.4.jar:2.5.4]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:345) ~[spring-boot-2.5.4.jar:2.5.4]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.4.jar:2.5.4]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.4.jar:2.5.4]
    at cni.tn.CniApp.CniAppApplication.main(CniAppApplication.java:34) ~[classes/:na]
Caused by: java.lang.IllegalArgumentException: argument "src" is null
    at com.fasterxml.jackson.databind.ObjectMapper._assertNotNull(ObjectMapper.java:4693) ~[jackson-databind-2.11.1.jar:2.11.1]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3478) ~[jackson-databind-2.11.1.jar:2.11.1]
    at cni.tn.CniApp.CniAppApplication.lambda$0(CniAppApplication.java:46) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:791) ~[spring-boot-2.5.4.jar:2.5.4]
    ... 5 common frames omitted**

The problem is the usage of constructors with parameters. Jackson can't map this by default. I think, there are two options:

  1. Add the default constructor and all required getters and setters.
  2. Add @JsonCreator to your paramized constructor.

For example:

public class Bean {
    public int id;
    public String name;

    @JsonCreator
    public Bean(
      @JsonProperty("id") int id, 
      @JsonProperty("theName") String name) {
        this.id = id;
        this.name = name;
    }
}

I am not sure, if you really need @JsonProperty for the parameters of the constructor, if you are using spring boot!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM