I am modelling classes in Java to store a JSON , for a particular JSON
"id":1,
"firstName":"sample",
"lastName":"person",
"Books":{
"bookName":"gone with the wind"
"isbn": 12345
}
I created a class person
with int id , String firstName
etc... what would be the best way to store bookName , make a class Books
with a String bookName
and int isbn
, how would I represent books in the person class , As an array? since books always has only one value is there a better way to represent it
For json serialization/deserialization, I suggest the jackson library.Here is my code,it works fine on my computer!
I store the json in the file named json.data as following:
{"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();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.