【问题标题】:how to read correctly a complex object sent to the back-end如何正确读取发送到后端的复杂对象
【发布时间】:2021-08-07 09:33:52
【问题描述】:

编辑: 经过一些提示后,我编辑了我的代码,现在我创建了一个对象,它包含我打算拥有的所有数据,所以现在我有一个由一个 int 和一个内部有一个数组的另一个对象的数组组成的对象 这是对象的代码:

export class tempfp{
mesi: fp[] = []
id:number=0;}



export class fp{
arr:number[]=new Array();}

这是我之前将数据发送到后端的操作 (注意对象 data 是 any 类型,对象 send 是 tempfp)

async onSubmit() {
console.log("start: \n"+JSON.stringify(this.data))
for (let i = 0; i < this.data.length; i++) {
  let m = new fp();
  Object.assign(m.arr, JSON.stringify(this.data[i]));
  this.send.mesi[i] = m;
}
this.send.id=this.id;
this.efp.postarray(this.send)//i even tried to put in this function this.data instead of this.send
 }}

在我的后端我有相同的对象,但是当我使用 http post 发送数据时,当我尝试从后端操作数据时,它确实没有正确读取它,我在浏览器中收到错误 500 ,如果我尝试在后端打印这个东西,它看起来是空的

【问题讨论】:

  • 例如,您可以发送一个包含 idarray 的 json-object,然后在 springboot-service 中创建一个代表该请求的相应类并将其设置为处理程序方法的参数。
  • @Turing85 我现在要试试
  • 确保在 spring-boot 中配置处理程序方法以使用 application/json (@PostMapping(..., consumes = MediaType.APPLICATION_JSON)) 类型的内容。

标签: javascript java typescript spring-boot


【解决方案1】:

一个post请求只能有一个body,而你已经在传递一个body,你需要做的是在java中创建一个模型来代表你想要传递的body,然后从前端传递它。

//I like to use lombok's @Data annotation to generate getters setters 
//and default constructor but you can also write them by hand
@Data 
public class MyBody {

   private String eff;

   private int id;

}

然后在您的控制器中,您将接受广告正文此模型的实例。

@PostMapping("takearrfp")
public void takearr(@RequestBody MyBody body) {
   String eff = body.getEff();
   int id = body.getId(); //And then do what you want whit this
   efps.readAndSave(eff);
}

此时剩下要做的就是将此模型作为主体传递,因此您需要将具有相同字段的对象作为发布请求的主体传递

{
   eff: put something here,
   id: put the id here
}

【讨论】:

  • 谢谢你的帮助@fabrizio,我按照你说的做了,现在我有另一个问题,如果你想再次帮助我,我编辑了问题,再次感谢你!
【解决方案2】:

你要做的很简单。正如另一个答案也说你一次只能通过一个身体。所以如果你想包含 id 那么你必须把它放到正文中。试试下面的代码

const  body = {
    id: id,
    arr: arr
    }
const obj = JSON.stringify(body)

然后,您可以使用 Fabrizio 回答中建议的方法从后端读取这些数据。

【讨论】:

  • 好的,所以我应该使用 this.data 将所有 matrik 发送到后端,而不是 arr,对吧?
  • const body = { id: id, arr: this.data }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
  • 1970-01-01
相关资源
最近更新 更多