gpt4 book ai didi

Spring @Requestbody 未映射到内部类

转载 作者:行者123 更新时间:2023-12-02 19:00:45 29 4
gpt4 key购买 nike

我正在使用 Spring 4.x 做 Spring Rest Api 项目

这有效:

Controller.java

@PostMapping("newTransaction")
TransactionRequestModel insertNewTransaction(@RequestBody TransactionRequestModel model){
//do something
}

TransactionRequestModel.java

public class TransactionRequestModel {
private int id;
private List<KeyValue> keyValueList;
public TransactionRequestModel(){}
//default constructor
//getter-setter
}

KeyValue.java

public class KeyValue {

String key;
String value;
//default constructor
//setter-getter
}

请求正文 Json

{
"id": 1
"keyValueList": [
{
"key": "dummy",
"value": "dummy"
}
]
}

使用 Jackson 的 Spring 消息转换器工作正常。

这不会:

当我将 TransactionRequestModel.java 更改为以下内容时(并删除 KeyValue.java)

public class TransactionRequestModel {

public class KeyValue {
String key;
String value;
//default constructor
//setter-getter
}
private int id;
private List<KeyValue> keyValueList;
public TransactionRequestModel(){}
//default constructor
//getter-setter
}

意味着,将KeyValue作为内部类,出现以下错误。

org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: No suitable constructor found for type [simple type, class com.example.model.TransactionRequestModel$KeyValue]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)

为什么?

SO 中的所有相关帖子都提到了第一种情况。我想知道为什么这行不通。请帮忙。

最佳答案

您必须使内部类静态

public class TransactionRequestModel {

public static class KeyValue {
String key;
String value;
//default constructor
//setter-getter
}
private int id;
private List<KeyValue> keyValueList;
public TransactionRequestModel(){}
//default constructor
//getter-setter
}

关于Spring @Requestbody 未映射到内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40398216/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com