Great Deals

Convert Java Object List to Json Array

14:39 suresh chaudhari 0 Comments


Code for demonstrating the Conversion of Java Object to Json Array

Jars Required:

  • http://central.maven.org/maven2/com/google/code/gson/gson/2.3.1/gson-2.3.1.jar<br/>
  • http://repo.grails.org/grails/repo/org/immutables/gson/2.1.0.alpha/gson-2.1.0.alpha.jar


import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.model.Product;
import com.google.gson.reflect.TypeToken;
/**
 * Servlet implementation class UserController
 */
@WebServlet("/users")
public class UserController extends HttpServlet {
private static final long serialVersionUID = 1L;
     
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserController() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products=new ArrayList<Product>();
products.add(new Product(1, "Pen", "Smooth Pencil", 23));
com.google.gson.Gson gsonObj=new Gson();
Type listTypes=new TypeToken<List<Product>>(){}.getType();
//;
PrintWriter pw=response.getWriter();
pw.write(gsonObj.toJson(products,listTypes));
pw.close();
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}

0 comments:

Advertising