【问题标题】:json parse error post data spring boot mysqljson解析错误发布数据spring boot mysql
【发布时间】:2021-11-18 03:34:56
【问题描述】:

当我从 Angular 发布数据表单时,我在后端遇到了这个问题,请有人帮助我我尝试通过对象映射器解决这个问题,但我不太明白如何正确地做到这一点 错误是:

  • 已解决 [org.springframework.http.converter.HttpMessageNotReadableException:JSON 解析错误:无法构造 entity.Group 的实例(尽管至少存在一个 Creator):没有从字符串值反序列化的字符串参数构造函数/工厂方法(' { “idGrp”:2, “nomGroup”:“内联网” }');嵌套异常是 com.fasterxml.jackson.databind.exc.MismatchedInputException:无法构造 entity.Group 的实例(尽管至少存在一个 Creator):没有从字符串值反序列化的字符串参数构造函数/工厂方法('{ “idGrp”:2, “nomGroup”:“内联网” }') 在 [来源:(PushbackInputStream);行:1,列:236](通过引用链:entity.Employe["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;
    }


}

我正在尝试发布包含实体组数据的员工数据 班级员工

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;
    }


}

控制器

 @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);
        }

请帮助我如何将json数据转换为我现在花费两天的对象在这个错误中

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());
                
            }

输出:

**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**

【问题讨论】:

  • 这是控制台中表单发送的数据:地址:“4270”年龄:“20”代码P:“2087”描述:“”电子邮件:“jkca@gmail.com”组:“ {\n \"idGrp\": 2,\n \"nomGroup\": \"intranet\"\n}" matricule: "125" nom: "" nom_ar: "jack" numTele: "0335890562" prenom: " " prenom_ar: "" ville: "突尼斯" [[Prototype]]: 对象
  • 您好,这有帮助吗:stackoverflow.com/q/45110371/12089702?如果不能,你可以提供一个类似于我链接的帖子中的minimal reproducible example

标签: java json spring spring-boot jsonparser


【解决方案1】:

问题在于使用带参数的构造函数。默认情况下,杰克逊无法映射它。我认为,有两种选择:

  1. 添加默认构造函数以及所有必需的 getter 和 setter。
  2. 将@JsonCreator 添加到您的参数化构造函数中。

例如:

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;
    }
}

我不确定,如果你真的需要@JsonProperty作为构造函数的参数,如果你使用的是spring boot!

【讨论】:

  • 是的,我正在使用 speig 启动应用程序,我这样做了 @JsonCreator 和属性,但它返回相同的错误
  • 现在在主类中创建这个方法:@Bean public CommandLineRunner run(ServiceEmp ServiceEmp) {return args->{ Employe e=new Employe(0,"","","","" ,0,"","",0,0,"",""); ObjectMapper objectMapper=new ObjectMapper(); TypeReference TypeReference =new TypeReference() {}; InputStream InputStream=TypeReference.class.getResourceAsStream(objectMapper.writeValueAsString(ServiceEmp.addEmp(e)));试试 {e=objectMapper.readValue(InputStream,TypeReference); ServiceEmp.addEmp(e); System.out.print("已保存");} catch(IOException a) {System.out.print("未保存"+a.getMessage()); }};
猜你喜欢
  • 2017-11-18
  • 2019-12-04
  • 2019-07-26
  • 2018-11-30
  • 2018-12-26
  • 2019-03-16
  • 2021-09-12
  • 2019-05-19
  • 2019-10-08
相关资源
最近更新 更多