LoginSignup
5
3

More than 5 years have passed since last update.

springでbeanをJSONとしてファイル出力

Posted at

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>

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;
    }
}

出力例

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

他の制御項目

基本的にはjacksonなので、他にやりたいことがあれば大抵はぐぐれば出てくる。

以下はその一例。

キーをキャメルケースからスネークケースに変換

import com.fasterxml.jackson.databind.PropertyNamingStrategy;

mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

出力例。

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

キーを任意の値に変更


@JsonProperty("alternateId")
private String hogeId;

Stringとして出力

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

JSONの整形が不要な場合

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

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

出力例。

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3