用于在JSON中存储嵌套元素的数据结构

时间:2013-03-19 01:59:28

标签: java json data-modeling

我正在用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 BooksString bookName创建int isbn,如何在人类中表示书籍,作为数组?因为书籍总是只有一个值,所以有更好的方式来表示它

1 个答案:

答案 0 :(得分:1)

对于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();
        }
    }

}