How To Get the List of JSON Objects With Spring RestTemplate

  • Post last modified:January 25, 2024
  • Reading time:4 mins read

Reading JSON Response using RestTemplate in Spring Boot

Introduction

  • JSON is a common data exchange format when building disparate systems that interact with each other.
  • For example, think about a GET request that is made to a rest endpoint. Most commonly JSON payload is returned as a response to the client from the server.
  • In this article, we will learn how to read and convert this JSON object to Java a object when using RestTemplate.

Reading Collection of JSON objects

  • Let’s say we have a rest endpoint that returns a list of user accounts that exist in the company database.
  • We will make a rest call to the endpoint, read the returned JSON data, and parse it into Java objects with Spring RestTemplate.

Implementation

  • JSON data that we receive from the endpoint looks like below. It’s an array of JSON objects.
[
     {
        "userId": 1048,
        "username": "username_fa58221c-b491-40ae-88ce-0c4be7af5903",
        "password": "password_q1234",
        "email": "username_fa58221c-b491-40ae-88ce-0c4be7af5903@gmail.com",
        "createdOn": "2023-05-01T00:00:43.698+00:00",
        "lastLogin": "2023-05-01T00:00:43.698+00:00",
        "permission": null
     },  
     .......  
     {
        "userId": 1124,
        "username": "username_f05ddbe2-3f36-44c5-9fd5-9df96d123192",
        "password": "password_q1234",
        "email": "username_f05ddbe2-3f36-44c5-9fd5-9df96d123192@gmail.com",
        "createdOn": "2023-05-29T00:38:54.445+00:00",
        "lastLogin": "2023-05-29T00:38:54.445+00:00",
        "permission": null
     }
]

DTOs

  • We need to create an Account POJO that maps the JSON properties to Java properties.
public class Account {
    private int userId;
    private String username;
    private String password;
    private String email;
    private Timestamp createdOn;
    private Timestamp lastLogin;
    private Permission permission;
    
    // getters and setters
}

Service

  • Now our service endpoint makes a call to the rest endpoint and reads the response as an Account array. Here Account is a POJO that maps to all the parameters that we receive from the JSON response.
  • To read a collection of accounts, we can read it as an Array of Accounts.
@Service
public class AccountService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("http://localhost:8080/accounts")
    private String url;

    public Account[] getAllAccounts() {
        return restTemplate
                .getForObject(url, Account[].class);
    }
}

If we print our mapped response :

Accounts: [Account{userId=1048, username='username_fa58221c-b491-40ae-88ce-0c4be7af5903', password='password_q1234', email='username_fa58221c-b491-40ae-88ce-0c4be7af5903@gmail.com', createdOn=2023-04-30 20:00:43.698, lastLogin=2023-04-30 20:00:43.698, permission=null} ..]

Reading Collection of Nested JSON objects

  • Now let’s say we receive nested collections of JSON objects. For example, we can we can have a collection of customers, where each customer can have a collection of credit cards issued to them.
[
    {
        "id": 10,
        "name": "jenny",
        "creditCard": [
            {
                "id": 11,
                "cardNumber": "2344323432112222",
                "expiryDate": "2023-04-10"
            },
            {
                "id": 10,
                "cardNumber": "2344323432112422",
                "expiryDate": "2023-04-12"
            },
            {
                "id": 13,
                "cardNumber": "4111111111111111",
                "expiryDate": "2023-04-11"
            },
            {
                "id": 14,
                "cardNumber": "4111111131111111",
                "expiryDate": "2023-05-11"
            },
            {
                "id": 15,
                "cardNumber": "4111111131119111",
                "expiryDate": "2023-05-12"
            },
            {
                "id": 17,
                "cardNumber": "378282246310005",
                "expiryDate": "2023-05-09"
            },
            {
                "id": 18,
                "cardNumber": "378282246710005",
                "expiryDate": "2024-05-09"
            },
            {
                "id": 21,
                "cardNumber": "4111111131119",
                "expiryDate": "2025-05-12"
            }
        ]
    }
]

Implementation

  • For nested objects, we can follow a similar approach, where we read the response as a customer array.
  • Now each customer can have multiple credit cards, so to appropriately map response, we need to set POJO such that where customer includes a collection of credit cards.

POJOs

  • Our POJO needs to include properties from the JSON response.
  • If the name of the property between JSON and Java is not the same, then we need to use @JsonProperty(“”) on the Java property to be able to map correctly.
public class Customer{

    private Long id;
    private String name;
    
    @JsonProperty("creditCard")
    private List<CreditCard> creditCards;
    
    // getters , setters ..
}


public class CreditCard {

    private Long id;
    private String cardNumber;
    private String expiryDate;
}

Service

  • The service class makes calls to the rest endpoint using RestTemplate, which also takes the mapper class to map the response to POJO.
  • Here we are using an array of Customers since JSON includes a collection of customers with creditCards.
@Service
public class CustomerService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("http://localhost:8080/customer/all")
    private String url;

    public Customer[] getAllCustomers() {
        return restTemplate
                .getForObject(url, Customer[].class);
    }
}

  • If we print our mapped response :
Customers: [Customer{id=10, name='jenny', creditCards=[CreditCard{id=11, cardNumber='2344323432112222', expiryDate='2023-04-10'}, ....]

Conclusion

  • In this article, we covered how to read the JSON response with Spring RestTemplate. We looked into a reading collection of JSON objects along with a nested collection.

Note: Although RestTemplate is widely used RestClient , its been deprecated since Spring 5 in favor of WebClient

Before You Leave

Checkout interview helping contents:

Leave a Reply