File output bean as JSON in spring

pom.xml

pom.xml


	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
	</dependencies>

File output using ObjectWriter

package kagamihoge.tojsonfile;

import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

import lombok.AllArgsConstructor;
import lombok.Data;

@SpringBootApplication
public class BeanToJsonFileApplication implements CommandLineRunner {
	public static void main(String[] args) throws InterruptedException {
		SpringApplication.run(BeanToJsonFileApplication.class, args).close();
	}

	@Bean
	public ObjectWriter writer() {
		ObjectMapper mapper = new ObjectMapper();
		ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
		return writer;
	}

	@Autowired
	ObjectWriter writer;

	@Override
	public void run(String... args) throws Exception {
		List<Sub> subList = Arrays.asList(new Sub(1, true), new Sub(2, true));
		Top top = new Top("hogeId", null, subList);

		writer.writeValue(Paths.get("json.txt").toFile(), top);
	}

	@Data
	@AllArgsConstructor
	static class Top {
		private String hogeId;
		private String nullValue;
		private List<Sub> subList;
	}

	@Data
	@AllArgsConstructor
	static class Sub {
		private int subId;
		private boolean bool;
	}
}

Output example

{
  "hogeId" : "hogeId",
  "nullValue" : null,
  "subList" : [ {
    "subId" : 1,
    "bool" : true
  }, {
    "subId" : 2,
    "bool" : true
  } ]
}

Other control items

It's basically jackson, so if you have something else you want to do, it usually comes out.

The following is an example.

Convert key from camel case to snake case

import com.fasterxml.jackson.databind.PropertyNamingStrategy;

mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

Output example.

{
  "hoge_id" : "hogeId",
  "null_value" : null,
  "sub_list" : [ {
    "sub_id" : 1,
    "bool" : true
  }, {
    "sub_id" : 2,
    "bool" : true
  } ]
}

Change the key to any value


@JsonProperty("alternateId")
private String hogeId;

Output as String

System.out.println(writer.writeValueAsString(top));

If you don't need JSON formatting

import com.fasterxml.jackson.core.util.MinimalPrettyPrinter;

ObjectWriter writer = mapper.writer(new MinimalPrettyPrinter());

Output example.

{"null_value":null,"sub_list":[{"sub_id":1,"bool":true},{"sub_id":2,"bool":true}],"alternateId":"hogeId"}

Recommended Posts

File output bean as JSON in spring
Output Spring Boot log in json format
Fitted in Spring Boot using a bean definition file named application.xml
Static file access priority in Spring boot
Local file download memorandum in Spring Boot
Output Notes document as XML document in Java
DI SessionScope Bean in Spring Boot 2 Filter
Output request and response log in Spring Boot
How to bind to property file in Spring Boot
[Java] Something is displayed as "-0.0" in the output
@Import target is treated as @Configuration in spring
[Spring Batch] Output table data to CSV file
How to test file upload screen in Spring + Selenium
Java11: Run Java code in a single file as is
Gzip-compress byte array in Java and output to file
Read JSON in Java
Spring bean life cycle
Parse Json in Scala
Use Interceptor in Spring
Microservices in Spring Cloud
POST JSON in Java
Output triangle in Ruby
Get cookies in Spring
Output in multiples of 3
Authenticate 3 or more parameters in JSON format using Spring Security
Create API to send and receive Json data in Spring
Output relative path in .classpath file generated by gradle eclipse
Response header may not be output correctly in Spring Security 4.1
Set up Multipart Resolver to allow file uploads in Spring