Arasto
Arasto

Reputation: 491

Convert Integer to JSON

I'm playing around in SpringBoot and i want to count the amount of users in my database.

UserRepository

public interface UserRepository extends JpaRepository<User, Long> {
    @Query(value = "select COUNT(*) from user", nativeQuery = true)
    Integer findAllActiveUsers();
}

UserService

    public Integer amountOfUsersInDB() {
        return userRepository.findAllActiveUsers();
    }

UserController

    @GetMapping("/myusers")
    public ResponseEntity amountOfUsers() {
        System.out.println(userService.amountOfUsersInDB());
        return ResponseEntity.ok(userService.amountOfUsersInDB());
    }




When i make the http get call it returns the amount of users inside my database as an Integer. How can i make it return the value as an JSON so i can later on dsplay it on my frontend?

Upvotes: 0

Views: 560

Answers (1)

cassiomolin
cassiomolin

Reputation: 130917

When you have something like this:

@GetMapping(value = "/count", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Integer> getCount() {
    Integer count = 1;
    return ResponseEntity.ok(count);
}

You'll have the following response payload which, by the way, is a valid JSON:

1

Now, if you want to produce a JSON object, then you could use a Map<String, Object> for representing the payload:

@GetMapping(value = "/count", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getCount() {

    Integer count = 1;

    Map<String, Object> payload = new HashMap<>();
    payload.put("count", count);

    return ResponseEntity.ok(payload);
}

Or you could define a class representing the payload, create and instance of such class and assign a value to the count field:

@Data
public class CountPayload {
    private Integer count;
}
@GetMapping(value = "/count", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CountPayload> getCount() {

    Integer count = 1;

    CountPayload payload = new CountPayload();
    payload.setCount(count);

    return ResponseEntity.ok(payload);
}

Upvotes: 1

Related Questions