How To Read a JSON File and Return Its Content in a Spring Boot API
Tags: java, programming, softwaredevelopment, softwareengineering
Published: 2024-01-19 21:20:50

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.

3. **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`](https://mvnrepository.com/artifact/commons-io/commons-io) and [`org.json`](https://mvnrepository.com/artifact/org.json/json/20220320) to your project's dependencies.

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

```xml
<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:

```groovy
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:

```json
{
  "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 ](https://writech.run/wp-content/uploads/2023/08/image-61.png)

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

```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

```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`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/ClassPathResource.html) 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`](https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html) representation of `staticDataResource` is passed to the `IOUtils.toString()` function. This `commons-io` utility function will convert it into a `String` variable.

Finally, the `staticDataString` variable is used to initialize a [`JSONObject`](https://stleary.github.io/JSON-java/org/json/JSONObject.html) instance, whose `Map<String, Objcet>` representation obtained with the [`toMap()`](https://stleary.github.io/JSON-java/org/json/JSONObject.html#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:

```json
{
  "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.
  
***
_The post "[How To Read a JSON File and Return Its Content in a Spring Boot API](https://writech.run/blog/how-to-read-a-json-file-and-return-its-content-in-a-spring-boot-api-1f69e552f7af/)" appeared first on [Writech](https://writech.run)._