【发布时间】:2021-12-10 01:31:08
【问题描述】:
我收到一个错误:com.fasterxml.jackson.databind.exc.MismatchedInputException: 无法反序列化 `java.util.ArrayList
可能是因为我在 Main 中的 ObjectMapper 或 Entity 中的 ArrayList 期间的数据类型错误... 我不知道如何修复它,因为我似乎不明白错误具体在哪里,或者我是否应该以不同的方式解决它(即:不在 main 中执行业务逻辑并创建一个 serviceImpl 和也许是一个 dto 包。
我猜这个问题有两个方面:(1)如何解决这个错误。 (2)在restAPIs中标记json数据的标准化最佳方法是什么,然后我们可以通过弄乱url进行排序。即 localhost:8080/recipes?name=scrambledEggs
1) JSON 文件
"recipes": [
{
"name": "scrambledEggs",
"ingredients": [
"1 tsp oil",
"2 eggs",
"salt"
],
"instructions": [
"Beat eggs with salt",
"Heat oil in pan",
"Add eggs to pan when hot",
"Gather eggs into curds, remove when cooked",
"Salt to taste and enjoy"
]
},
{
"name": "garlicPasta",
"ingredients": [
"500mL water",
"100g spaghetti",
"25mL olive oil",
"4 cloves garlic",
"Salt"
],
"instructions": [
"Heat garlic in olive oil",
"Boil water in pot",
"Add pasta to boiling water",
"Remove pasta from water and mix with garlic olive oil",
"Salt to taste and enjoy"
]
2) 实体
public class RecipesInfo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private ArrayList<RecipesFile> recipes;
//get + set
public class RecipesFile {
private String name;
private ArrayList<String> ingredients;
private ArrayList<String> instructions;
//get + set
3) 主文件
ublic class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
@Bean
CommandLineRunner runner(RecipesService recipesService) {
return args -> {
ObjectMapper mapper = new ObjectMapper();
TypeReference<ArrayList<RecipesInfo>> typeReference = new TypeReference<ArrayList<RecipesInfo>>() {};
InputStream inputStream =TypeReference.class.getResourceAsStream("/json/data.json");
try {
ArrayList<RecipesInfo> recipes = mapper.readValue(inputStream, typeReference);
recipesService.save(recipes);
System.out.println("data saved: recipes");
} catch (IOException e) {
System.out.println("unable to save data: recipes");
System.out.println(e);
}
};
【问题讨论】:
标签: java jackson objectmapper