Skip to content

Instantly share code, notes, and snippets.

@mjtoolbox
Created May 8, 2013 05:57
Show Gist options
  • Save mjtoolbox/5538527 to your computer and use it in GitHub Desktop.
Save mjtoolbox/5538527 to your computer and use it in GitHub Desktop.
Simple Servlet using JEE7 JsonObjectBuilder
package mypackage;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class JsonTester
*/
@WebServlet("/JsonTester")
public class JsonTester extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public JsonTester() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add("person", Json.createObjectBuilder().add("firstName", "Michael").add("lastName", "Jo"));
JsonObject result = builder.build();
StringWriter sw = new StringWriter();
try(JsonWriter writer = Json.createWriter(sw))
{
writer.writeObject(result);
}
out.print(sw.toString());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment