import java.io.IOException;
import javax.servlet.ServletOutputStream;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import Smart.RongCard.Result.BaseProtocol;
/**
* JSON接口
* @author wenyuan
*/
public class WriteJson {
private static ObjectMapper mapper = new ObjectMapper();
private static JsonFactory factory = mapper.getJsonFactory();
public static void writeJSON(ServletOutputStream output, BaseProtocol obj,int code) throws IOException {
JsonGenerator JGenerator = null;
if(code == BaseProtocol.CHARSET_CODE_UTF8){
JGenerator = factory.createJsonGenerator(output, JsonEncoding.UTF8);
}
if(JGenerator != null){
JGenerator.writeObject(obj);
}
}
}
//Head接口
public class Head {
String result;//true or false
String errcode;//1003:请求不存在
String errmsg;//汉字描述
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getErrcode() {
return errcode;
}
public void setErrcode(String errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
}
//Body接口
public class Body {
}
//BaseProtocol接口
public class BaseProtocol {
public static final String RETURN_FORMAT_JSON = "json";
public static final int CHARSET_CODE_UTF8 = 0;
private Head head;
private Body body;
public Head getHead() {
return head;
}
public void setHead(Head head) {
this.head = head;
}
public Body getBody() {
return body;
}
public void setBody(Body body) {
this.body = body;
}
}
//代码接口调用方法
protocol.setHead(head);
protocol.setBody(body);
WriteJson.writeJSON(response.getOutputStream(), protocol, BaseProtocol.CHARSET_CODE_UTF8);
第二种解析方法
//这里面放的就是jsonobj
JSONArray jsonarray = new JSONArray();
//这里面放的类似于Map一样的东西
JSONObject jsonobj = new JSONObject();
List<DeviceInfo> deviceinfo = appService.getalldevice();
List<String> list = new ArrayList<String>();
for(DeviceInfo devinfo:deviceinfo){
list.add(devinfo.getdId());
}
jsonobj.put("dId", list);
jsonarray.add(jsonobj);
WriteJson.writeJSON(response.getOutputStream(), jsonarray, 0);