日期:2014-05-16  浏览次数:20383 次

接口----将数据转换成Json格式,给别人做接口调用
因为工作需要,要求把数据库中的数据提取出来转换成Json格式 给别人作为接口调用。
这里面 用到了将java对象保存在JSON中。 然后通过ajax来得到 json转化成js对象的数据
说的有点绕,直接上代码。

在Jsp中
<%@ page import=java.io.Writer%>
<%@ page import="org.json.JSONArray"%>
<%@ page import="org.json.JSONObject"%>
public class Tsdh {
    private String depname;
    private String name;
	private String tel;
    public void setName(String name) {
      this.name = name;
    }
    public String getName() {
      return this.name;
    }
    public void setDepname(String depname) {
      this.depname = depname;
    }
    public String getDepname() {
      return this.depname;
    }
	public void setTel(String tel) {
      this.tel = tel;
    }
    public String getTel() {
      return this.tel;
    }
  }

JSONArray jsons=new JSONArray();

try{
  Tsdh  tsdh=new Tsdh();
  tsdh.setDepname("办公室");
  tsdh.setName("大熊");
  tsdh.setTel("0431-1111111");

  Tsdh tsdh2=new Tsdh();
  tsdh2.setDepname("行政部");
  tsdh2.setName("柯基");
  tsdh2.setTel("0431-2222222");
  
  JSONObject json=new JSONObject(tsdh);
  JSONObject json1=new JSONObject(tsdh2);
  
  jsons.put(json);
  jsons.put(json1);

  response.setContentType("text/html;charset=utf-8");

  Writer writer=response.getWriter();
  writer.writer(jsons.toString);
  writer.flush();
  writer.close();
  writer=null;
 }catch(Exception e){
   System.out.println("error: "+e);
}
  
}

<script type="text/javascript">
function createXMLHttpRequest(){
   var xmlHttp;
   if(window.ActiveObject){
       xmlHttp=new ActiveObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
       xmlHttp=new XMLHttpRequest();
}
  return xmlHttp;
}
function getTestInfo(){
  var xmlHttp=createXMLHttpRequest();
  xmlHttp.onreadystatechange=function(){
   if(xmlHttp.readyState==4){
      if(xmlHttp.status==200){
          var myJson=eval("("+xmlHttp.responseText+")");
         if(null!=myJson && ""!=myJson && myJson.length>0){
             for(var i=0;i<myJson.length;i++){
                         alert(myJson[i].name+"--"+myJson[i].depname+"--"+myJson[i].tel);
  
              }
             }

          }
     }
}
    xmlHttp.open("post","getValue.jsp");
    xmlHttp.send(null);
}
</script>
<input type="button" value="获取数据" onclick="getTestInfo()">