在java中转换嵌套的JSON

时间:2017-03-31 10:05:13

标签: java json jackson gson

我有兴趣将java转换为json并将此json作为我的最终输出:

{
"author":{
  "name":"John Doe",
  "age":"22"
 },
"title":{
  "bookTitle":"Cooking Guide",
  "isbn":"cvv4bbb4"
}
}

以下是我的java课程: Book.java

public class Book {
 public Author author;
 public Title title;
 public String availableStore;

    public String getAvailableStore() {
        return availableStore;
    }

    public void setAvailableStore(String availableStore) {
        this.availableStore = availableStore;
    }

    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }

    public Title getTitle() {
        return title;
    }

    public void setTitle(Title title) {
        this.title = title;
    }



 class Author{
  String name;
  String age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }

 }

 class Title{
 String bookTitle;
 String isbn;

        public String getBookTitle() {
            return bookTitle;
        }

        public void setBookTitle(String bookTitle) {
            this.bookTitle = bookTitle;
        }

        public String getIsbn() {
            return isbn;
        }

        public void setIsbn(String isbn) {
            this.isbn = isbn;
        }
 }

}

这是跑步者类 PrettyJsonPrin.java

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


public class PrettyJsonPrint
{
  public static void main(String[] args) throws Exception
  {
    Book book = new Book();

    book.author.setAge("b22");
    book.author.setName("james bond");
    book.title.setBookTitle("XXXX");
    book.title.setIsbn("3b3b3b");
    book.availableStore="Book store ";

    // using Gson API
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String bookJson = gson.toJson(book);
    System.out.println("pretty print json using Gson:\n" + bookJson);

    // using Jackson API
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    bookJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(book);
    System.out.println("pretty print json using Jackson:\n" + bookJson);
  }
}

当我运行程序时,收到此错误消息:

Exception in thread "main" java.lang.NullPointerException
    at com.brian.json.PrettyJsonPrint.main(PrettyJsonPrint.java:25)

请帮忙。

0 个答案:

没有答案