我正在用Java建模类来存储JSON,用于特定的JSON
"id":1,
"firstName":"sample",
"lastName":"person",
"Books":{
"bookName":"gone with the wind"
"isbn": 12345
}
我用class person
等创建了int id , String firstName
...
什么是存储bookName的最佳方式,使用class Books
和String bookName
创建int isbn
,如何在人类中表示书籍,作为数组?因为书籍总是只有一个值,所以有更好的方式来表示它
答案 0 :(得分:1)
对于json序列化/反序列化,我建议使用jackson库。这是我的代码,它在我的计算机上运行正常!
我将json存储在名为json.data的文件中,如下所示:
{"id":1,
"firstName":"sample",
"lastName":"person",
"books":[{"bookName":"gone with the wind","isbn":12345}]
}
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();
}
}
}