2017-05-19 22 views
-2
public class Town {  

    private Person p; 

    private String hello; 
    private long number; 
} 

public class Person { 

    private String firstName; 
    private double legs; 
    private String lastName; 
} 

我想寫使用下面的代碼如何閱讀對象的JSON文件到列表中的Java與傑克遜

ObjectMapper mapper = new ObjectMapper(); 
ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter()); 
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true))); 
writer.writeValue(out, townobj); 

將會產生的Json喜歡這個城市類JSON。

{ 
    "p" : { 
    "firstName" : "John", 
    "amount" : 6860.0, 
    "lastName" : "Smith" 
    }, 
    "hello" : "qwiejiowcqnio", 
    "number" : 1380.0 
} 

{ 
    "p" : { 
    "firstName" : "Sam", 
    "amount" : 623460.0, 
    "lastName" : "Smith" 
    }, 
    "hello" : "qwiej2342io", 
    "number" : 1330.0 
} 

如何從jackson中讀取嵌套對象轉換爲Java的輸出?

+1

所以你知道如何使用'mapper.writer()'。當看[ObjectMapper'](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html)的javadoc時,它不是很明顯,相反的操作會使用'mapper.reader()'? – Andreas

回答

2

如果你想讀的兩個對象爲列表到Java,你需要將它們寫一個清單,以及:

List<Town> towns = new ArrayList<>(); 
towns.add(townobj); 
towns.add(anotherTownobj); 

writer.writeValue(out, towns); 

當你讀到這回它又變成了一個列表。

您在問題中顯示的輸出不是有效的單個json文件。但使用上述方法將得到一個有效的單個json文件,如下所示:

[ 
    { 
     "p" : { 
     "firstName" : "John", 
     "amount" : 6860.0, 
     "lastName" : "Smith" 
     }, 
     "hello" : "qwiejiowcqnio", 
     "number" : 1380.0 
    }, 
    { 
     "p" : { 
     "firstName" : "Sam", 
     "amount" : 623460.0, 
     "lastName" : "Smith" 
     }, 
     "hello" : "qwiej2342io", 
     "number" : 1330.0 
    } 
] 
+0

Thankyou爲了這個答案。如果我有一個像上面這樣的現有JSON文件,如何將更多的對象附加到文件中的數組中? –