JSON 反对 Java

JSON to object in Java

我有以下 JSON:

{
       "book":{
             "isbn" : "12356789",
             "title" : "Algorithm",
             "author" : [
                           "Cormen",
                           "Rivest",
                           "Stein"
             ],
             "price" : 45.78
       }
}

我需要将这个 JSON 字符串转换成一本书 class。我不想通过 属性 将其设置为 属性。还有,我不想用Gson。

我想做的事情是:

Book book=jsonReader.readObject().toClass(Book.class);

如何使用 javax.json.JsonMoxy 来实现?

我已经使用 Jackson 解析器来执行此操作。看看 ObjectMapper class。

public static <T> Object getObjectFromJsonString(String json,
        Class<T> className) throws JsonParseException,
        JsonMappingException, IOException {
    InputStream is = new ByteArrayInputStream(json.getBytes("UTF-8"));
    return objectMapper.readValue(is, className);
}

我建议不要使用 Jackson 以外的任何东西来处理 json。

您粘贴的 JSON 基于 Jackson 的解决方案类似于:-

首先为您的图书对象创建一个 POJO

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class BookVO {

    private final String isbn;
    private final String title;
    private final String[] author;
    private final double price;

    @JsonCreator
    public BookVO(@JsonProperty("isbn") final String isbn, @JsonProperty("title") final String title, @JsonProperty("author") final String[] author, @JsonProperty("price") final double price) {
        super();
        this.isbn = isbn;
        this.title = title;
        this.author = author;
        this.price = price;
    }

    public String getIsbn() {
        return isbn;
    }

    public String getTitle() {
        return title;
    }

    public String[] getAuthor() {
        return author;
    }

    public double getPrice() {
        return price;
    }

}

然后你需要一个 Book 容器 POJO

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Books {

    private final BookVO book;

    @JsonCreator
    public Books(@JsonProperty("book") final BookVO book) {
        super();
        this.book = book;
    }

    public BookVO getBook() {
        return book;
    }
}

最后需要将JSON转换为Java对象如下:-

public static void main(final String[] args) throws JsonParseException, JsonMappingException, IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final Books books = mapper.readValue(new File("book.json"), Books.class);

    System.out.println(books);

}

book.json的内容是

{
       "book":{
             "isbn" : "12356789",
             "title" : "Algorithm",
             "author" : [
                           "Cormen",
                           "Rivest",
                           "Stein"
             ],
             "price" : 45.78
       }
}

感谢您的回答。 如果我使用 Jackson,我将不得不在我的项目中添加另一个库(这是我不想做的事情) 我在这里 http://blog.bdoughan.com/2013/07/eclipselink-moxy-and-java-api-for-json.html

找到了问题的答案