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>
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;
}
}
{
"hogeId" : "hogeId",
"nullValue" : null,
"subList" : [ {
"subId" : 1,
"bool" : true
}, {
"subId" : 2,
"bool" : true
} ]
}
It's basically jackson, so if you have something else you want to do, it usually comes out.
The following is an example.
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
} ]
}
@JsonProperty("alternateId")
private String hogeId;
System.out.println(writer.writeValueAsString(top));
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