1

I am trying to convert from json to Java object. I am receiving a json string that includes a list of books:

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

And I have created an object called 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
}

Also I am using the doGet method to retrieve this data from a RESTful webservice in this way:

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

    }

However, I am getting an error when executing: List books = new Gson().fromJson(jsonBooks, new TypeToken>(){}.getType());

The exception is the next:

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)

enter image description here

enter image description here

The output with Java list: Criptography 6, Jonathan Khatz, Jonathan Khatz, 2010 SelfAdaptiveSystem, Hausi Muller, Hausi Muller, 2010

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

Cheers

5
  • java.lang.NoClassDefFoundError: com/google/gson/Gson. Looks like you forgot to add the Gson library. Jun 30, 2015 at 7:11
  • Hi Boris, they are included in the import area: import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; Jun 30, 2015 at 7:14
  • Yes, that we know - otherwise you would not have been able to compile. You also must have included the .jar in your compile time classpath. But you have not got the .jar on your run time classpath - i.e. in the WEB-INF/lib folder of the .war. Jun 30, 2015 at 7:15
  • the libraries are included in EAR Libraries. I included as an external java file through java Built Path. Jun 30, 2015 at 7:26
  • They exist in in the project but are not copied into the build. Find out why. Jun 30, 2015 at 7:47

2 Answers 2

1

I did this, since this how I always use 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);

And it works fine. Also I renamed Books to Book since the class represents only one book.

2
  • Sorry, I got a mistake that I can not figure out what is happening in the next: Books[] booksA = gson.fromJson(jsonBooks, Books[].class); Arrays.asList(booksA).forEach(System.out::println); I am getting an error: The Method forEach (in the type iterable <Books> is not applicable for the arguments (PrintStream) Jun 30, 2015 at 20:05
  • Thank you, I have updated the question with the solution that you provided me. I change a little bit because I got some troubles. Jun 30, 2015 at 20:53
-1

not sure if this is exactly what you need.. but I'm using gson like this.

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

1
  • This is only tangentially related to the question. Certainly not an answer. Jun 30, 2015 at 8:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.