package pack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.simple.*;
public class JsonMake extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("EUC-KR");
String sabun = new String((request.getParameter("sabun")).getBytes("8859_1"),"euc-kr");
String irum = new String((request.getParameter("irum")).getBytes("8859_1"),"euc-kr");
String juso = new String((request.getParameter("juso")).getBytes("8859_1"),"euc-kr");
response.setContentType("text/xml; charset=euc-kr");
response.setHeader("Cache-control", "no-cache");
if (sabun != null && irum != null && juso != null) {
// String jsonStr = createJson(sabun,irum,juso);
// String jsonStr = createJson2(sabun,irum,juso);
String jsonStr = createJson3(sabun,irum,juso);
response.getWriter().write(jsonStr);
} else {
response.getWriter().write("?");
}
}
private String createJson(String sabun, String irum, String juso) {
StringBuffer sb = new StringBuffer("\r\n{\"jikwon\":");
sb.append("\r\n{\"sabun\":\""+sabun+"\",");
sb.append("\r\n\"irum\":\""+irum+"\",");
sb.append("\r\n\"juso\":\""+juso+"\"}");
sb.append("\r\n}");
return sb.toString();
}
//jsonObject 라이브러리 이용
private String createJson2(String sabun, String irum, String juso) {
JSONObject obj=new JSONObject();
JSONObject obj1=new JSONObject();
obj.put("sabun",sabun);
obj.put("irum",irum);
obj.put("juso",juso);
obj1.put("jikwon", obj);
System.out.print(obj1.toString());
//result : {"jikwon":{"irum":"한국인","juso":"서울시 중구","sabun":"10"}}
return obj1.toString();
}
//jsonArray
private String createJson3(String sabun, String irum, String juso) {
JSONObject obj1=new JSONObject();
JSONArray array=new JSONArray();
for(int i=0;i<2;i++){
JSONObject obj=new JSONObject();
obj.put("sabun",sabun);
obj.put("irum",irum);
obj.put("juso",juso);
array.add(obj);//see above
}
obj1.put("jikwon", array);
System.out.println(obj1.toString());
//result : {"jikwon":[{"irum":"한국인","juso":"서울시 중구","sabun":"10"},{"irum":"한국인","juso":"서울시 중구","sabun":"10"}]}
return obj1.toString();
}
}