Skip to content

How To Read a JSON File and Return Its Content in a Spring Boot API

Mocking an API with a static JSON file in Java and Kotlin

I recently had to produce an API that was supposed to return extremely complex and nested data. Building it would have required hundreds of queries, and my team was in a hurry. This is why we decided to mock that API with a JSON file containing the expected data, manually written by a data scientist.

I could have returned the JSON file directly from the API, but that was not the idea. Instead, the endpoint was supposed to read the JSON file from a project’s folder, turn it into a Java object, and return it serialized to JSON as any Spring Boot API would normally do. All this in the fastest way and with the simplest logic possible.

Let’s now learn how to build an API in Spring Boot that reads a static JSON file and returns its content via Jackson.

Why an API Might Need To Return the Contents of a JSON File

There are at least two good reasons why reading the contents of a static JSON file and returning it via an API is useful. Let’s dig into them.

  1. Your API response never changes: In this case, the response can be produced only once and can be cached in a static JSON file. This is especially useful when the API response is complex or involves a nested structure.
  2. To mock an API response: Using a static JSON file as a data source for the API response is a good and fast way to mock an API.

From JSON File to API Response in Spring Boot

Let’s now see how to build an API that reads a JSON file and returns its content in Spring Boot, both in Java and Kotlin.

Prerequisites

First, you have to add commons-io.ommons-io and org.json to your project’s dependencies.

If you are a Maven user, add the following dependency to your project’s POM file:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20220320</version>
</dependency>

Otherwise, if you are a Gradle user, add this dependency to your project’s build file:

implementation group: 'commons-io', name: 'commons-io', version: '2.11.0'
implementation group: 'org.json', name: 'json', version: '20220320'

Now, you have everything required to achieve the goal of the tutorial.

Building an API That Reads a Static JSON File

First, let’s take a look at the static JSON file:

{
  "name": "Maria",
  "surname": "Williams",
  "age": 35
}

Note that this is just a simple example. Your static JSON file is likely to be much more complex.

Then, place the static-data.json file in the Spring Boot’s resources folder, as shown below:

Note the “static-data.json” file in the “resources” folder
Note the “static-data.json” file in the “resources” folder

Now, you are ready to read the JSON file and return its content. Let’s see how to achieve this in both Java and Kotlin.

Java

package com.demo.controllers;

import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@RestController
@RequestMapping
class CustomController {
    @GetMapping("/mocked-api")
    public ResponseEntity<Map<String, Object>> getRadarData() throws IOException {
        ClassPathResource staticDataResource = new ClassPathResource("static-data.json");
        String staticDataString = IOUtils.toString(staticDataResource.getInputStream(), StandardCharsets.UTF_8);

        return new ResponseEntity<>(
            new JSONObject(staticDataString).toMap(),
            HttpStatus.OK
        );
    }
}

Kotlin

package com.demo.controllers

import org.apache.commons.io.IOUtils
import org.json.JSONObject
import org.springframework.core.io.ClassPathResource
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import java.nio.charset.StandardCharsets

@RestController
@RequestMapping
class CustomController {
    @GetMapping("/mocked-api")
    fun getMockedData() : ResponseEntity<MutableMap<String, Any>> {
        val staticDataResource = ClassPathResource("static-data.json")
        val staticDataString = IOUtils.toString(staticDataResource.inputStream, StandardCharsets.UTF_8.name())
        
        return ResponseEntity(
            JSONObject(staticDataString).toMap(),
            HttpStatus.OK
        )
    }
}

As you can see, ClassPathResource is used to load static-data.json into the staticDataResource variable. If you are not familiar with ClassPathResource, this is a Spring Boot class for loading resources placed in the resouces folder.

Then, the InputStream representation of staticDataResource is passed to the IOUtils.toString() function. This commons-io utility function will convert it into a String variable.

Finally, thestaticDataString variable is used to initialize a JSONObject instance, whose Map<String, Objcet> representation obtained with the toMap() method is returned as the API response.

The Map<String, Objcet> object with .toMap() will be converted by Jackson into the following 200 HTTP content-type: application/json response:

{
  "name": "Maria",
  "surname": "Williams",
  "age": 35
}

This exactly matches the content of the static-data.json file.

Et voilà! You just implemented an API that reads a static JSON file and returns its content in Spring Boot.

Conclusion

In this article, you learned how to use static JSON files in your Spring Boot Java or Kotlin application. Specifically, you saw how to implement an API that reads a static JSON file and returns its content in content-type: application/json format. This is particularly useful for mocking an API in a couple of lines of code or for implementing APIs whose response never changes.

Thanks for reading! I hope that you found this article helpful.

nv-author-image

Antonello Zanini

I'm a software engineer, but I prefer to call myself a Technology Bishop. Spreading knowledge through writing is my mission.View Author posts

Want technical content like this in your blog?