简体   繁体   English

将数据发布到 api 时解析 Json 异常

[英]Parse Json exception while posting data to api

Hello all I am trying to save some post data from related tables.大家好,我正在尝试从相关表中保存一些发布数据。 Cities and halls.城市和大厅。 Here is my City model这是我的城市模型

package com.example.model;
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 = "cities")

public class Cities {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;

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

public int getId() {
    return id;
}

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

public String getName() {
    return name;
}

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



}

Here is my Halls model:这是我的霍尔模型:

package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
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 java.util.Date;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Entity
@Table(name = "halls")

public class Halls {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

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

     @Column(name = "placeqty")
     private int placeqty;
      
     @JsonIgnoreProperties({"hibernateLazyInitializer", "handler","ignoreUnknown = true"})
    
     @ManyToOne(fetch = FetchType.LAZY, optional = false)
        @JoinColumn(name = "cityid", nullable = false)
        @OnDelete(action = OnDeleteAction.CASCADE)
        private Cities cityid;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getPlaceqty() {
        return placeqty;
    }

    public void setPlaceqty(int placeqty) {
        this.placeqty = placeqty;
    }

    public Cities getCityid() {
        return cityid;
    }

    public void setCityid(Cities cityid) {
        this.cityid = cityid;
    }
     
     
}

It is related on column cityid to cities model.它与 cityid 列与城市模型相关。 Here is my controller method to create a new hall in Spring boot:这是我在 Spring Boot 中创建新大厅的控制器方法:

@RequestMapping(value="/add", method=RequestMethod.POST)
        public ResponseEntity add(@RequestBody Halls hall)
        {
         hallsService.addHall(hall);
          return new ResponseEntity<>(hall, HttpStatus.CREATED);

        }

And my Angular form:还有我的 Angular 形式:

<p>Добавить зал</p>
<div>
  <div class="submit-form">
    <div *ngIf="!submitted">
      <div class="form-group">
        <label for="title">Название</label>
        <input
          type="text"
          class="form-control"
          id="title"
          required
          [(ngModel)]="hall.name"
          name="name"
        />
      </div>


      <div class="form-group">
        <label for="placeqty">кол-во мест</label>
        <input
          type="text"
          class="form-control"
          id="placeqty"
          required
          [(ngModel)]="hall.placeqty"
          name="placeqty"
        />
      </div>

      <select  [(ngModel)]="hall.cityid" name="cityid">
        <option *ngFor="let c of cities" value="{{c.id}}">{{c.name}}</option>
      </select>`


      <button (click)="saveHall()" class="btn btn-success">Сохранить</button>
    </div>

    <div *ngIf="submitted">
      <h4>Зал добавлен!</h4>
      <button class="btn btn-success" (click)="newHall()">Добавить еще</button>
    </div>
  </div>
</div>

And my component looks like this:我的组件如下所示:

import { Component, OnInit } from '@angular/core';
import { Hall } from 'src/app/models/hall.model';
import { City } from 'src/app/models/city.model';

import { HallService } from 'src/app/services/hall.service';
import { CityService } from 'src/app/services/city.service';


@Component({
  selector: 'app-add-hall',
  templateUrl: './add-hall.component.html',
  styleUrls: ['./add-hall.component.css']
})
export class AddHallComponent implements OnInit {
  cities?: City[];

  // @ts-ignore
  hall: Hall = {
    name: '',
    placeqty:'',
    cityid:this.retrieveCities(),




  };
  submitted = false;

  constructor(private  hallService:HallService,private cityService:CityService) { }

  ngOnInit(): void {
  }
  saveHall(): void {
    const data = {
      name: this.hall.name,
      placeqty: this.hall.placeqty,
      cityid: this.hall.cityid

    };
    console.log(data.cityid);
    this.hallService.create(data)
      .subscribe(
        response => {
        console.log("city")
          console.log(response);
          this.submitted = true;
        },
        error => {
          console.log(error);
        });
  }
  newHall(): void {
    this.submitted = false;
    this.hall = {
      name: '',
      placeqty: '',
      cityid: this.retrieveCities()


    };
  }

  retrieveCities(): any {
   this.cityService.getAll()
      .subscribe(
        data => {
          this.cities = data;
          console.log(data);
          return data;
          },
        error => {
          console.log(error);
      return error;
        });

  }
}

And my Halls model:还有我的霍尔模型:

import {City} from "./city.model";

export class Hall {
  id?:any;
  name?:string;
  placeqty?:string;

  cityid?:City;

}

So, after posting this form I get the following error:因此,在发布此表单后,我收到以下错误:

 2021-11-01 11:34:10.236  WARN 14120 --- [io-8888-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.example.model.Cities` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('2'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.example.model.Cities` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('2')
     at [Source: (PushbackInputStream); line: 1, column: 43] (through reference chain: com.example.model.Halls["cityid"])]

What am I doing incorrectly in this case?在这种情况下我做错了什么?

Will add my city model from Java and Angular将从 Java 和 Angular 添加我的城市模型

Java:爪哇:

package com.example.model;
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 = "cities")

public class Cities {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;

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

public int getId() {
    return id;
}

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

public String getName() {
    return name;
}

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


    

}

And the angular part of it:和它的角度部分:

export class City {
  id?:any;
  name?:string;
}

Where exectly I have to convert it?我必须在哪里转换它? Here is my post payload:这是我的帖子有效载荷:

name: "test", placeqty: "100", cityid: "2"}
cityid: "2"
name: "test"
placeqty: "

Also I tryed to use ngvalue instead of a value:我也尝试使用 ngvalue 而不是一个值:

 <select  [(ngModel)]="hall.cityid" name="cityid">
        <option *ngFor="let c of cities" [ngValue]='c.id'>{{c.name}}</option>
      </select>

With no luck.没有运气。

com.example.model.Halls["cityid"])] com.example.model.Halls["cityid"])]

"no String-argument constructor/factory method to deserialize from String value ('2')" “没有字符串参数构造函数/工厂方法从字符串值('2')反序列化”

the problem is in your JSON you are probably sending the ID as a string.问题出在您的 JSON 中,您可能将 ID 作为字符串发送。 make sure the field is a number.确保该字段是一个数字。

Finaly I got it fixed.最后我把它修好了。 I edited the selectbox with cities this way:我用这种方式编辑了带有城市的选择框:

<select  [(ngModel)]="hall.cityid" name="cityid">
        <option *ngFor="let city of cities" [ngValue]="city">{{city.name}}</option>

      </select>

And it fixed the problem.它解决了这个问题。

You need to add an all argumenet contractor.您需要添加一个 all argumenet 承包商。 Or you can use @AllArgsConstructor or @Data from Lombok.或者您可以使用来自 Lombok 的 @AllArgsConstructor 或 @Data。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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