0

I"m currently building a React/Springboot application and my goal is to return single object from the Array but objects are not valid in react, Does anyone know how to I could pull the data from the object inside JSON Array or if there is a method I could put in my controller that would format the objects inside the array as mini arrays?

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

Here is my Controller for the above json data:

 @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;
    }

1 Answers1

1

You can use the following code to do the same, you can directly return your object and, spring will convert your Java Object to JSON. By default, Jackson is used to doing the parsing of Object to JSON. You just need to mark your class as @RestController and return the object as is. Read this Returning JSON object as response in Spring Boot post for more details this post has more details to topic. Also, make sure that you have Spring Web dependencies from start.spring.io selected so you'll get RestController with it otherwise, Add dependency to your pom file.

Code :

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 on webpage: Output of above code on client side

keypoints to remember: Use getters and setters in your class, because internally they are being used by Jackson to fetch your object data.

Akash Jain
  • 316
  • 2
  • 10