Created
May 8, 2013 05:57
-
-
Save mjtoolbox/5538527 to your computer and use it in GitHub Desktop.
Simple Servlet using JEE7 JsonObjectBuilder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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