【问题标题】:restAPI json array in Object extract对象提取中的rest API json数组
【发布时间】: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


    【解决方案1】:

    JSON 应该包含一个数组或 JSON 对象。在您的情况下,根据您的实体,您应该在 recipes 数组周围添加大括号

    {
        "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"
            ]
        ]
    }
          
    

    之后,您可以简单地反序列化单个 RecipesInfo 而不是它的集合

    RecipesInfo recipes = mapper.readValue(inputStream, RecipesInfo.class);
    

    另外,我注意到你的内部 RecipesFile 类不是 static。没有它,Object Mapper 将无法创建 RecipesFile 类的实例

    public class RecipesInfo {
    
        ...
        public static class RecipesFile {
            private String name;
            private ArrayList<String> ingredients;
            private ArrayList<String> instructions;
    
            //get + set
        ...
    

    关于第二个问题,可以查看以下Stackoverflow article

    【讨论】:

    • 嗨!感谢您的回复,我想我们越来越近了。所以,我的 json 文件并不完全有一个“id”,我在实体类中做了一个。我认为这是我错误的当前来源: Caused by: org.springframework.orm.jpa.JpaSystemException: could not serialize;嵌套异常是 org.hibernate.type.SerializationException:无法序列化。在不编辑 json 文件的情况下,最好的方法是什么?此外,我注意到您的链接指向 nodejs MEAN 堆栈解决方案,但我需要将其限制为 java。这方面还有其他线索吗?我在考虑 h2database...但是...
    • @Garen 请提供完整的堆栈跟踪以确定问题的原因。
    • @Garen 我提供的链接描述了 REST API 设计的最佳实践,它主要与语言无关。如果您需要 Spring Boot RestAPI 示例,可以查看 this tutorial
    猜你喜欢
    • 1970-01-01
    • 2019-03-22
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 2018-07-03
    相关资源
    最近更新 更多