2014-12-26 1 views

답변

4

JSON을 처리하는 데 Jackson library을 사용합니다. ObjectMapper 클래스는 POJO : s를 JSON으로, 그 반대로도 변환 할 수 있습니다. 그 외에도 아래 예제와 같이 파일 쓰기를 처리하기 위해 java.nio.file.Files 클래스를 사용할 것입니다.

// First, define some POJO 
public static class Pojo { 
    private final String content; 

    @JsonCreator 
    public Pojo(String content) { 
     this.content = content; 
    } 

    public String getContent() { 
     return content; 
    } 
} 

// This test simply illustrates file writing of JSON objects 
@Test 
public void testAppendToFile() throws IOException { 
    // The ObjectMapper is used to convert between Pojos and JSON (and vice versa) 
    final ObjectMapper mapper = new ObjectMapper(); 

    // Convert a Pojo to JSON 
    final String json1 = mapper.writeValueAsString(new Pojo("This is the content #1")); 

    // Write it to the file myfile.json. 
    // The first time the file is created and the content is NOT appended 
    Files.write(new File("myfile.json").toPath(), Arrays.asList(json1), StandardOpenOption.CREATE); 

    // Convert another Pojo to JSON 
    final String json2 = mapper.writeValueAsString(new Pojo("This is the content #2")); 

    // Write to the file again. 
    // The second time the content is appended (due to StandardOpenOption.APPEND) 
    Files.write(new File("myfile.json").toPath(), Arrays.asList(json2), StandardOpenOption.APPEND); 

    // Read the file and verify that there are 2 lines 
    final List<String> lines = Files.readAllLines(new File("myfile.json").toPath()); 
    Assert.assertEquals(2, lines.size()); 
} 
+1

절대적으로 환상적 .... 고맙습니다. – James

+0

코드가 도움이 되었습니까? – wassgren

관련 문제