{Java}JSONファイル読込

 

https://style.potepan.com/articles/27407.html
https://qiita.com/penguinshunya/items/353bb1c555f337b0cf6d
https://qiita.com/komiya_atsushi/items/c978e85c2065f57cea38


notepad User.java

public class User {
  public String firstName;
  public String lastName;
  public int age;
}


notepad a.java

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;

import java.io.*;
import java.nio.file.*;
import java.util.*;


public class a {
  public static void main(String[] args) throws Exception {
    
    String targetFilePath = null;
    String outPut = null;

    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    OutputStreamWriter osw = null;

    // テストファイル作成

    outPut = "./a.txt";

    fos = new FileOutputStream(outPut);
    bos = new BufferedOutputStream(fos);
    osw = new OutputStreamWriter(bos, "UTF-8");
    
    osw.write("[\n");
    osw.write("  {\"firstName\": \"太郎\", \"lastName\": \"山田\", \"age\": 25},\n");
    osw.write("  {\"firstName\": \"花子\", \"lastName\": \"五十嵐\", \"age\": 15}\n");
    osw.write("]\n");

    osw.close();
    bos.close();
    fos.close();


    String json = readAll("./a.txt");
    
    ObjectMapper mapper = new ObjectMapper();

    try {
      List<User> users = mapper.readValue(json, new TypeReference<List<User>>() {});

      for(int i =0; i< users.size(); i++ ) {
        System.out.println(users.get(i).firstName);
        System.out.println(users.get(i).lastName);
        System.out.println(users.get(i).age);
      }
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
  }

  // テキストファイル全体を読み込み文字列を返す
  public static String readAll(final String path) throws IOException {
    return Files.lines(Paths.get(path), Charset.forName("UTF-8")).collect(Collectors.joining(System.getProperty("line.separator")));
  }

}

 


javac -encoding utf-8 -classpath .;jackson-core-2.15.2.jar;jackson-annotations-2.15.2.jar;jackson-databind-2.15.2.jar a.java
java  -classpath .;jackson-core-2.15.2.jar;jackson-annotations-2.15.2.jar;jackson-databind-2.15.2.jar a