JsonGenerator 使用

Posted by Sir0xb on 2012-02-28 14:10:22 +0800

JsonGenerator 生成 JSON

@RequestMapping(value = "/json.sir")
    public void returnJson(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String userpass = request.getParameter("userpass");
 
        Writer out =response.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(out);
 
        jsonGenerator.writeStartObject();
        jsonGenerator.writeBooleanField("success", true);
        jsonGenerator.writeStringField("username", username);
        jsonGenerator.writeStringField("userpass", userpass);
        jsonGenerator.writeEndObject();
        jsonGenerator.flush();
 
//        jsonGenerator.writeStartObject(); 
//        jsonGenerator.writeFieldName("callback"); 
//            jsonGenerator.writeStartArray(); 
//                jsonGenerator.writeStartObject(); 
//                jsonGenerator.writeBooleanField("success", true); 
//                jsonGenerator.writeStringField("username", username); 
//                jsonGenerator.writeStringField("userpass", userpass); 
//                jsonGenerator.writeEndObject(); 
//            jsonGenerator.writeEndArray(); 
//        jsonGenerator.writeEndObject(); 
    }

 

JsonGenerator 生成 JSONP

@RequestMapping(value = "jsonp.sir")
public void returnJsonp(HttpServletRequest request,HttpServletResponse response) throws IOException {
    String username = request.getParameter("username");
    String userpass = request.getParameter("userpass");
    String callback = request.getParameter("callback");
 
    Writer sw = new StringWriter();
    ObjectMapper objectMapper = new ObjectMapper();
    JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(sw);
 
    sw.write(callback + "(");
    jsonGenerator.writeStartObject();
    jsonGenerator.writeBooleanField("success", true);
    jsonGenerator.writeStringField("username", username);
    jsonGenerator.writeStringField("userpass", userpass);
    jsonGenerator.writeEndObject();
    jsonGenerator.flush();
    sw.write(")");
    sw.close();
 
    Writer out =response.getWriter();
    out.write(sw.toString());
}

Copyright © 2022, Built with Gatsby