我有 json:
"taxLevels": [{
"code": "VAT",
"percentage": 19.0
}
]
这真是List<TTaxLevel>
我有Model.class:
public class Model{
private final List<TTaxLevel> taxLevels;
}
和TTaxLevel.class:
@NoArgsConstructor
public class TTaxLevel {
private String code;
private Double percentage;
}
但我在这里收到错误:
<块引用>[已解决
[org.springframework.http.converter.HttpMessageNotReadableException:
JSON 解析错误:无法反序列化的实例
java.util.LinkedHashMap
我能否以某种方式强制 jackson
在此处输入 ArrayList
而不是 Map
?这是一个问题。
这是反序列化代码:
Model model = new ObjectMapper().readValue(content, Model .class);
答案 0 :(得分:0)
请为您的类添加 getter/setter 方法并提供无参数构造函数。 另外你的json不是完全有效的,应该是:
{
"taxLevels": [
{
"code": "VAT",
"percentage": 19.0
}
]
}
我尝试将它放在资源文件夹中,获取并响应示例请求。这是示例代码:
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
class Model {
private List<TTaxLevel> taxLevels;
}
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
class TTaxLevel {
private String code;
private Double percentage;
}
@RequestMapping("tax-level")
@RestController
class SampleRequestBody {
private final ObjectMapper objectMapper;
SampleRequestBody(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@PostMapping
public Map<String, Model> taxLevel(@RequestBody Model model) throws JsonProcessingException {
final Map<String, Model> response = new HashMap<>(1);
response.put("data", model);
return response;
}
@GetMapping
public Model getTaxLevel() throws IOException {
InputStream inputStream = new ClassPathResource("tax-level.json").getInputStream();
return objectMapper.readValue(inputStream, Model.class);
}
}
答案 1 :(得分:0)
所以有两个问题:
{
"taxLevels": [{
"code": "VAT",
"percentage": 19.0
}
]
}