【问题标题】:How do i turn a nested JSON object to an array Spring boot?如何将嵌套的 JSON 对象转换为数组 Spring Boot?
【发布时间】:2021-05-27 11:44:46
【问题描述】:

我目前正在构建一个 React/Springboot 应用程序,我的目标是从数组中返回单个对象,但对象在反应中无效,有谁知道如何从 JSON 数组中的对象中提取数据,或者如果有一种方法可以放入我的控制器中,将数组内的对象格式化为迷你数组?

{
  - drinks: {
       id: 1,
       drinkId: null,
       drinkName: "Bloody Mary",
       glassType: "Highball",
       strAlcoholic: "Alcoholic",
       drinkDetails: "A Bloody Mary is a cocktail containing vodka, tomato juice, and other 
       spices and flavorings including Worcestershire sauce, hot sauces, garlic, herbs, 
       horseradish, celery, olives, salt, black pepper, lemon juice, lime juice and celery 
       salt.",
       720x720-primary-28cf1aaa79d0424d951901fcc0a42e91_xmhgw9.jpg"
    }
}

这是我对上述 json 数据的控制器:

 @GetMapping(path = "all/{id}")
    @CrossOrigin
    public @ResponseBody Map<String, Optional<Drink>> getById(@PathVariable Long id){
        Map<String, Optional<Drink>> response = new HashMap<>();
        response.put("drinks", drinkRepository.findById(id));

        return response;
    }

【问题讨论】:

    标签: java json reactjs spring-boot api


    【解决方案1】:

    你可以使用下面的代码来做同样的事情,你可以直接返回你的对象,spring会将你的Java对象转换为JSON。默认情况下,Jackson 习惯于将 Object 解析为 JSON。您只需将您的类标记为 @RestController 并按原样返回对象。阅读此Returning JSON object as response in Spring Boot 帖子以获取更多详细信息,此帖子包含有关主题的更多详细信息。 另外,请确保您选择了 start.spring.io 中的 Spring Web 依赖项,否则您将获得 RestController,否则,将依赖项添加到您的 pom 文件中

    代码:

    package com.example.demo;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class DemoController {
        class User {
            String name, age, job;
            public User(String name, String age, String job) {
                this.name = name;
                this.age = age;
                this.job = job;
            }
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public String getAge() {
                return age;
            }
    
            public void setAge(String age) {
                this.age = age;
            }
    
            public String getJob() {
                return job;
            }
    
            public void setJob(String job) {
                this.job = job;
            }
        }
        @GetMapping("/hello")
        public User greetings() {
            return new User("User", "18", "worker");
        }
    }
    
    

    网页输出: Output of above code on client side

    要记住的关键点: 在您的类中使用 getter 和 setter,因为 Jackson 在内部使用它们来获取您的对象数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-25
      • 2019-03-28
      • 2021-05-28
      • 2017-06-08
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      相关资源
      最近更新 更多