对于 json 序列化/反序列化,我建议使用 jackson 库。这是我的代码,它在我的计算机上运行良好!
我将 json 存储在名为 json.data 的文件中,如下所示:
{"id":1,
"firstName":"sample",
"lastName":"person",
"books":[{"bookName":"gone with the wind","isbn":12345}]
}
和代码,我省略了getter/setter
public class Book
{
private String bookName;
private int isbn;
}
public class BookWriter
{
private String id;
private String firstName;
private String lastName;
private Book[] books;
}
public class JSONTest
{
public static void main(String[] args)
{
try
{
ObjectMapper mapper = new ObjectMapper();
BookWriter writer=(BookWriter)mapper.readValue(new File("json.data"), BookWriter.class);
for(Book book:writer.getBooks())
{
System.out.println(book.getBookName()+","+book.getIsbn());
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}