Where The Streets Have No Name

spring에서 json, xml데이터 출력 본문

Developement/Java

spring에서 json, xml데이터 출력

highheat 2011. 10. 21. 14:12
@RequestMapping(value = "/test/Test2Json.do")
public void test2json(@RequestParam(value="name", required=false) String name, 
                                       HttpServletResponse response) throws IOException{
	System.out.println("name: "+name);
	JSONObject obj=new JSONObject();
	obj.put("name","홍길동");
	obj.put("num",new Integer(100));
    obj.put("balance",new Double(1000.21));
	obj.put("is_vip",new Boolean(true));
	obj.put("nickname",null);
    //out.write(obj.toJSONString());
	response.setContentType("application/json");	    
    response.setCharacterEncoding("utf-8");
	response.getWriter().write(obj.toJSONString());	    
}

 

@RequestMapping(value = "/test/Test3Xml.do")
public void test3xml(@RequestParam(value="name", required=false) String name, 
                                      HttpServletResponse response) throws IOException{
	Element carElement = new Element("car");        // root
        Document myDocument = new Document(carElement);        // 문서를 생성하고 엘리먼트를 추가..
         
        carElement.setAttribute(new Attribute("vin","vinvalue"));
         
        Element make = new Element("make");
         
        carElement.addContent(new Element("make").addContent("토요타"));         
        carElement.addContent(new Element("model").addContent("Celica"));
        carElement.addContent(new Element("year").addContent("1997"));
        carElement.addContent(new Element("color").addContent("green"));
        carElement.addContent(new Element("license").addContent("12ADFDS1").setAttribute("state","CA"));
        carElement.addContent(new Comment("차설명"));
         
        // Format을 맞추자.
        Format f = Format.getCompactFormat();
        f.setEncoding("utf-8");
        f.setIndent("    ");
        XMLOutputter outputter = new XMLOutputter(f);		
         
        //outputter.output(myDocument, out);
        response.setContentType("application/xml");	    
 	   response.setCharacterEncoding("utf-8");
 	   response.getWriter().write(outputter.outputString(myDocument));	
}