首页 > 解决方案 > 如何将嵌套的 JSON 对象转换为数组 Spring Boot?

问题描述

我目前正在构建一个 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;
    }

标签: javajsonreactjsspring-bootapi

解决方案


你可以使用下面的代码来做同样的事情,你可以直接返回你的对象,spring会将你的Java对象转换为JSON。默认情况下,Jackson 习惯于将 Object 解析为 JSON。您只需将您的类标记为 @RestController 并按原样返回对象。在 Spring Boot 帖子中阅读此Returning JSON object 作为响应以获取更多详细信息,此帖子包含有关主题的更多详细信息。此外,请确保您选择了 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");
    }
}

网页 输出:上述代码在客户端的输出

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


推荐阅读