如何使用 gson 将 json 转换为字符串

how to use gson to convert json to string

我正在尝试从 json 转换为 Java 对象。我收到一个 json 字符串,其中包含图书列表:

[{"author":"Jonathan Khatz",
 "id":8,
 "name":"Criptography  6",
 "publisher":"Chapman",
 "year":2010},
 {"author":"Hausi Muller",
 "id":9,
 "name":"SelfAdaptiveSystem",
 "publisher":"UVic",
 "year":2010}]

我创建了一个名为 Books 的对象:

package RESTful.client.model;

public class Books {
    private int id;
    private String name;
    private String author;
    private int year;
    private String publisher;

    public Books(){
    }

    public Books(int id, String name, String author, int year, String publisher){
        this.id=id;
        this.name=name;
        this.author=author;
        this.year=year;
        this.publisher=publisher;
    }

    // public Getter & Setter methods
}

我还使用 doGet 方法以这种方式从 RESTful 网络服务检索此数据:

package RESTful.client.getBooks;
import RESTful.client.model.*;

// imports omitted

/**
 * Servlet implementation class GetBooksByYear
 */
@WebServlet("/GetBooksByYear")
public class GetBooksByYear extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetBooksByYear() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        Client client= Client.create();
        //PrintWriter printWriter = response.getWriter();
        String year= request.getParameter("year");
        System.out.println("Year to search: "+year);                 
        WebResource webResource= client.resource("http://localhost:8080/library/webapi/books/year/"+year);
        ClientResponse rs=webResource.accept(
                           MediaType.APPLICATION_JSON_TYPE,
                           MediaType.APPLICATION_XML_TYPE).
                           get(ClientResponse.class);
        System.out.println("Get operation response processing...\n");
        String jsonBooks=rs.getEntity(String.class);

        //kajacx solution:
        Gson gson = new Gson();
        Books[] booksA = gson.fromJson(jsonBooks, Books[].class);
        List<Books> books = Arrays.asList(booksA);
        for(Books book : books) {
            System.out.println(book.getName()+", "+book.getAuthor()+", "+book.getAuthor()+", "+ book.getYear());
        }

    }

但是,我在执行时遇到错误: 列出书籍 = new Gson().fromJson(jsonBooks, new TypeToken>(){}.getType());

下一个例外:

java.lang.NoClassDefFoundError: com/google/gson/Gson
    RESTful.client.getBooks.GetBooksByYear.doGet(GetBooksByYear.java:60)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Java 列表的输出: 密码学 6,​​Jonathan Khatz,Jonathan Khatz,2010 SelfAdaptiveSystem, 豪斯穆勒, 豪斯穆勒, 2010

json书籍格式为:[{"author":"Jonathan Khatz","id":8,"name":"Criptography 6","publisher":"Chapman","year":2010},{"author":"Hausi Muller","id":9,"name":"SelfAdaptiveSystem","publisher":"UVic","year":2010}]

干杯

不确定这是否正是您所需要的..但​​我正在这样使用 gson。

Gson gson = new Gson(); Object json = gson.fromJson(stringJson, Class);

我这样做了,因为这是我一直使用 GSON 的方式:

Gson gson = new Gson();

String data = "[{\"author\":\"Jonathan Khatz\", \"id\":8,"
    + "\"name\":\"Criptography  6\","
    + "\"publisher\":\"Chapman\", \"year\":2010},"
    + "{\"author\":\"Hausi Muller\", \"id\":9,"
    + "\"name\":\"SelfAdaptiveSystem\","
    + "\"publisher\":\"UVic\", \"year\":2010}]";

Book[] books = gson.fromJson(data, Book[].class);
Arrays.asList(books).forEach(System.out::println);

而且效果很好。另外,我将 Books 重命名为 Book,因为 class 只代表一本书。