user3217883
user3217883

Reputation: 1465

How to return an array of objects in json format in spring boot?

Check out these two controller methods. They both use the same object. The first one, called backtestStrategy correctly returns a JSON formatted response. The second one, called getAllStrategies, returns an array of values not in JSON format. All the values are there but none of the keys.

@RestController
@RequestMapping("/api/v1")
public class StrategyController {
    @Autowired
    private StrategyService strategyService;

    @GetMapping("/backtest")
    public Response backtestStrategy(@RequestParam String strategyName, @RequestParam String symbol) {
        Response response = strategyService.backtestStrategy(strategyName,symbol);
        return response;
    }
    
   @GetMapping("/strategies")
   public List<Response> getAllStrategies() {
        List<Response> strategies = strategyService.getAllStrategies();
        return strategies;
    }
}

Suggestions?

EDIT: The first one apparently works because I create the Response object, populate it, save it to a db, and return the created object. The second one is reading from the db. The values are in the db correctly.

Here is the order of operations: controller calls service implementation which is defined by an interface. Service implementation calls repository, which makes the db query. Here is the query:

@Query(value="select * from strategy", nativeQuery = true)
List<Response> getAllStrategies();

Upvotes: 2

Views: 12759

Answers (1)

Tushar
Tushar

Reputation: 657

You can use the following example to get the desired response:

Pojo.java

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class Pojo {
    private String name;
}

DemoRestController.java

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/api/v1")
public class DemoRestController {
  @GetMapping("/single")
  public ResponseEntity<Pojo> single() {

    return ResponseEntity.ok(new Pojo("one"));
  }

  @GetMapping("/multiple")
  public ResponseEntity<List<Pojo>> multiple() {
    return ResponseEntity.ok(Arrays.asList(new Pojo("one"), new Pojo("two")));
  }
}

Output - Single

{
"name": "one"
}

Output - Multiple

[
   {
    "name": "one"
   },
   {
    "name": "two"
   }
]

Upvotes: 1

Related Questions