How to Include and Use GSON library in Eclipse project

I'm from the PHP background, so pardon my noobness. I'm required to use JSON in one of my projects and I cannot, for the life of me, determine how to import and use the GSON library.

I followed Adding library to Eclipse and Using GSON threads but for some reason my code isn't working.

The aim is to pass an ArrayList object back as a JSON array so that I can use Jquery (inside Ajax success function) to iterate over it.

But when I use the following (This is not a class, simply a jsp file which connects to database, pulls some info, and stores it in an ArrayList):

<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%
String kw = request.getParameter("key");
try {
java.sql.Connection con;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/abcd", "root", "pass");
st = con.createStatement();
rs = st.executeQuery("SELECT DISTINCT t.tckid FROM ticket t  WHERE t.tckid LIKE '%"+kw+"%'"); 
ArrayList<String> tickets = new ArrayList<String>();
while(rs.next()) {
        String TCKTID = rs.getString(1);
        tickets.add(TCKTID);
}
rs.close();
st.close();
con.close();        
Gson gson = new Gson(); // this is giving me Gson cannot be resolved to a type

So of what I can gather, the Gson class didn't get imported at all. Is there a way to verify the successful import of the library? Or do I also need to use some import *** code on the top of the file?

Upvotes: 3

Views: 9501

Answers (1)

Ker p pag
Ker p pag

Reputation: 1588

The problem is that you are not importing the Gson package in your current JSP.

<%

Gson gson=new Gson();

%>

importing in JSP

<%@ page import="com.google.gson.Gson" %>

but please keep in mind to avoid using scriptlets in your JSPMVC pattern to separate the server side with the client side actions/purpose. if you want to display values coming from the database you could always use JSTL and using different scopes(request scope,session scope, etc).

Upvotes: 3

Related Questions