java - 尝试从 Angular 向 Spring Boot API 插入数据时出现 "JSON parse error: Cannot construct instance of"错误

标签 java spring angular spring-boot

我有一个 Angular 表单,我正在调用 post 方法来插入数据。但是我无法插入数据,因为我收到如下错误:

"JSON parse error: Cannot construct instance of `com.ashwin.springsecurityangular.model.AuditorGroup` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.ashwin.springsecurityangular.model.AuditorGroup` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1')
 at [Source: (PushbackInputStream); line: 1, column: 17] (through reference chain: com.ashwin.springsecurityangular.model.AssignmentAudit["auditorGroup"])"

通过 Angular 形式作为AssignmentAudit的数据是:

enter image description here

我调用的API是: AssignmentAuditController:当我尝试打印 System.out.println(register.getAssignmentDate()) 时,我得到“null”作为输出。

@PostMapping(value = "/assignment-audit/create")
    public AssignmentAudit postCustomer(@RequestBody AssignmentAudit register) {
        System.out.println(register.getAssignmentDate());
        /*  Selection selection=selectionRepository.getOne(request.)*/
        System.out.println("entered assignment  audit");
        AssignmentAudit _rRegister = assignmentAuditRepository.save(new AssignmentAudit(register.getAuditorGroup(),register.getAssignmentDate(),register.getSelection(),register.getMagNo()));
        return _rRegister;
    }

AssignmentAudit.java

package com.ashwin.springsecurityangular.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
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.OnDelete;
import org.hibernate.annotations.OnDeleteAction;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
@Table(name = "assignmentaudit")
public class AssignmentAudit implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "auditorGroupId", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private AuditorGroup auditorGroup;

    @Column(name = "assignmentDate")
    private String assignmentDate;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "selectionId", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Selection selection;

    @Column(name="mag_no")
    private int magNo;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public AssignmentAudit(AuditorGroup auditorGroup, String assignmentDate, Selection selection, int magNo) {

        this.auditorGroup = auditorGroup;
        this.assignmentDate = assignmentDate;
        this.selection = selection;
        this.magNo = magNo;
    }

    public AuditorGroup getAuditorGroup() {
        return auditorGroup;
    }

    public void setAuditorGroup(AuditorGroup auditorGroup) {
        this.auditorGroup = auditorGroup;
    }

    public Selection getSelection() {
        return selection;
    }

    public void setSelection(Selection selection) {
        this.selection = selection;
    }

    public int getMagNo() {
        return magNo;
    }

    public void setMagNo(int magNo) {
        this.magNo = magNo;
    }

    public String getAssignmentDate() {
        return assignmentDate;
    }

    public void setAssignmentDate(String assignmentDate) {
        this.assignmentDate = assignmentDate;
    }

    public AssignmentAudit() {

    }


    @Override
    public String toString() {
        return "AssignmentAudit [id=" + id + ", auditorGroup=" + auditorGroup + ", assignmentDate=" + assignmentDate
                + "]";
    }






}

AuditGroup.java

package com.ashwin.springsecurityangular.model;

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 = "auditor_group")
public class AuditorGroup implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long auditorGroupId;

    @Column(name="group_desc")
    private String groupDesc;

    @Column(name="from_date")
    private String fromDate;

    @Column(name="to_date")
    private String toDate;

    public long getAuditorGroupId() {
        return auditorGroupId;
    }

    public void setAuditorGroupId(long auditorGroupId) {
        this.auditorGroupId = auditorGroupId;
    }

    public String getGroupDesc() {
        return groupDesc;
    }

    public void setGroupDesc(String groupDesc) {
        this.groupDesc = groupDesc;
    }

    public String getFromDate() {
        return fromDate;
    }

    public void setFromDate(String fromDate) {
        this.fromDate = fromDate;
    }

    public String getToDate() {
        return toDate;
    }

    public void setToDate(String toDate) {
        this.toDate = toDate;
    }

    public AuditorGroup() {

    }

    public AuditorGroup(String groupDesc, String fromDate, String toDate) {
        this.groupDesc = groupDesc;
        this.fromDate = fromDate;
        this.toDate = toDate;
    }



}

选择.java

package com.ashwin.springsecurityangular.model;

import java.io.Serializable;
import java.util.Date;

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

import org.hibernate.annotations.GeneratorType;

@Entity
@Table(name="selection")
public class Selection implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long selectionId;

    @Column(name="selection_date")
    private String selectionDate;

    @Column(name="selected_by")
    private String selectedBy;

    @Column(name="pan_exim_number")
    private Long panEximNumber;

    @Column(name="name")
    private String name;

    @Column(name="address")
    private String address;

    @Column(name="phone_number")
    private String phoneNumber;

    @Column(name="selection_type")
    private String selectionType;

    @Column(name="consignment_no")
    private String consignentNo;

    @Column(name="consignment_date")
    private String consignentDate;


    @Column(name="selection_period_from_date")
    private String selectionPeriodFromDate;

    @Column(name="selection_period_to_date")
    private String selectionPeriodToDate;

    @Column(name="agent_no")
    private Long agentNo;

    @Column(name="custom_office")
    private String customOffice;

    @Column(name="auditor_group")
    private boolean auditorGroup=false;


    public Long getSelectionId() {
        return selectionId;
    }

    public void setSelectionId(Long selectionId) {
        this.selectionId = selectionId;
    }

    public String getSelectionDate() {
        return selectionDate;
    }

    public void setSelectionDate(String selectionDate) {
        this.selectionDate = selectionDate;
    }

    public String getSelectedBy() {
        return selectedBy;
    }

    public void setSelectedBy(String selectedBy) {
        this.selectedBy = selectedBy;
    }

    public Long getPanEximNumber() {
        return panEximNumber;
    }

    public void setPanEximNumber(Long panEximNumber) {
        this.panEximNumber = panEximNumber;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getSelectionType() {
        return selectionType;
    }

    public void setSelectionType(String selectionType) {
        this.selectionType = selectionType;
    }

    public String getConsignentNo() {
        return consignentNo;
    }

    public void setConsignentNo(String consignentNo) {
        this.consignentNo = consignentNo;
    }

    public String getConsignentDate() {
        return consignentDate;
    }

    public void setConsignentDate(String consignentDate) {
        this.consignentDate = consignentDate;
    }


    public String getSelectionPeriodFromDate() {
        return selectionPeriodFromDate;
    }

    public void setSelectionPeriodFromDate(String selectionPeriodFromDate) {
        this.selectionPeriodFromDate = selectionPeriodFromDate;
    }

    public String getSelectionPeriodToDate() {
        return selectionPeriodToDate;
    }

    public void setSelectionPeriodToDate(String selectionPeriodToDate) {
        this.selectionPeriodToDate = selectionPeriodToDate;
    }

    public Long getAgentNo() {
        return agentNo;
    }

    public void setAgentNo(Long agentNo) {
        this.agentNo = agentNo;
    }

    public String getCustomOffice() {
        return customOffice;
    }

    public void setCustomOffice(String customOffice) {
        this.customOffice = customOffice;
    }

    public Selection() {

    }

    @Override
    public String toString() {
        return "Selection [selectionId=" + selectionId + ", selectionDate=" + selectionDate + ", selectedBy="
                + selectedBy + ", panEximNumber=" + panEximNumber + ", name=" + name + ", address=" + address
                + ", phoneNumber=" + phoneNumber + ", selectionType=" + selectionType + ", consignentNo=" + consignentNo
                + ", consignentDate=" + consignentDate + ", selectionPeriodFromDate=" + selectionPeriodFromDate
                + ", selectionPeriodToDate=" + selectionPeriodToDate + ", agentNo=" + agentNo + ", customOffice="
                + customOffice + "]";
    }

    public boolean isAuditorGroup() {
        return auditorGroup;
    }

    public void setAuditorGroup(boolean auditorGroup) {
        this.auditorGroup = auditorGroup;
    }









}

现在 Angular 文件: 分配审计.ts

export class AssignmentAudit {
    id: number;
    auditorGroup: number;
    assignmentDate: string;
    selectionNumber: number;
}

Angular 分配审核表单:

<form name="form" #f="ngForm" (ngSubmit)="f.form.valid &&  onSubmit()" novalidate class="">
          <div class="form-group row">
            <div class="col-md-6">
              <label for="auditorGroup">Auditor Group</label>
              <select class="form-control" id="auditorGroup" required [(ngModel)]="assignmentAudit.auditorGroup" name="auditorGroup"
                #auditorGroup="ngModel"
                [ngClass]="{ 'is-invalid': f.submitted && auditorGroup.invalid }"
                required
                >
                <option *ngFor="let title of auditorgroups" [value]="title.auditorGroupId">{{title.groupDesc}}</option>

              </select>
              <div *ngIf="f.submitted && auditorGroup.invalid" class="invalid-input">
                <div *ngIf="auditorGroup.errors?.required">Auditor Group is required</div>
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label for="assignmentDate">Assignment Date</label>
                <input type="date" id="assignmentDate"  class="form-control" name="assignmentDate" placeholder="Please enter the Asignment Date" [(ngModel)]="assignmentAudit.assignmentDate" #assignmentDate="ngModel"
                [ngClass]="{ 'is-invalid': f.submitted && assignmentDate.invalid }"
                required />
                <div *ngIf="f.submitted && assignmentDate.invalid" class="invalid-input">
                  <div *ngIf="assignmentDate.errors?.required">Assignment Date is required</div>
                </div>
              </div>
            </div>
          </div>


          <button type="submit" style="margin-bottom: 50px;" class="btn btn-success pull-right">Submit</button>
        </form>

我的表单如下所示:

enter image description here

我从 component.ts 文件调用服务类的方法是

this.assignmentAuditService.createRegister(this.assignmentAudit).subscribe(data => console.log(data), error => console.log(error));

调用api的assignment-audit.service类:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class AssignmentAuditService {

    private baseUrl = 'http://localhost:8080/api/assignment-audit';

    constructor(private http: HttpClient) { }

    createRegister(assignmentAudit: Object): Observable<Object> {
    return this.http.post(`${this.baseUrl}` + `/create`, assignmentAudit);
  }

}

最佳答案

assignmentaudit.ts的属性

id: number;
auditorGroup: number;
assignmentDate: string;
selectionNumber: number;

@RequestBody AssignmentAudit register 中映射的对象要求不匹配它包含属性,

private long id;
private AuditorGroup auditorGroup;
private String assignmentDate;
private Selection selection;
private int magNo;

这里auditorGroupselection是对象,但您将字符串传递给 auditorGroup这是无效的。这就是异常(exception)情况。

您需要更改assignmentaudit.ts根据AssignmentAudit.class或者创建与请求正文匹配的新对象并将其放在 @RequestBody AssignmentAudit register 的位置。它会起作用的。

关于java - 尝试从 Angular 向 Spring Boot API 插入数据时出现 "JSON parse error: Cannot construct instance of"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53183430/

相关文章:

Java Applet + JNI + .so 文件

java - 使用 keystore 生成签名的APK

spring - 将 RedeliveryPolicy 注入(inject) Spring 启动 ActiveMQ

java - Spring :为什么在单元测试中加载应用程序上下文时需要添加javax.el-api依赖项?

java - Spring mockMvc 在我的测试中不考虑验证

Angular 2 如何相对于另一个元素定位一个元素

javascript - 如何正确实现带id的路由?

angular - 如何在 Angular2 组件模板中引用 "this"?

java - 地址已在使用 : JVM_Bind but no process is listed using port with netstat

java - 在模态窗口中打开 YouTube 播放器 API