J2EE中的struct中的json数据接收和发送

来源:互联网 发布:网络科学导论讲义 编辑:程序博客网 时间:2024/04/29 03:55

首先我们通过ServletContext获得request和response然后调用下面的类就可以实现接送数据的接受和转发了

json包的解析和打包我更喜欢使用gson。不过都是构造字符串,解析字符串而已。

package com.edu.AutomotiveSMSystem.action;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


 


import com.edu.AutomotiveSMSystem.model.Volume;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class getjson {

HttpServletRequest request;
 HttpServletResponse response ;
 
 PrintWriter out ;
 public getjson( HttpServletRequest request,HttpServletResponse response) throws IOException
 {
 
 this.request=request;
 
 this.response=response;
 
    request.getSession();
 
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
this.out = response.getWriter();
 
 
 }
 
 
 
 public JSONObject doget() throws IOException
 {
   BufferedReader reader = request.getReader();
       StringBuffer buffer = new StringBuffer();
       String string;
       while ((string = reader.readLine()) != null) {
           buffer.append(string);
           
       }
 reader.close();
       
      System.out.println(request.getParameter("pn")  );
     
 JSONObject myget=JSONObject.fromObject("{pn:18291445124}");
 
 return  myget;
 
 }
 
 
 public void outstring(String words)
 {
JSONObject myoutJsonObject=JSONObject.fromObject(words);

out.println(myoutJsonObject);
 
 
 }
 
 public void outar(int []arr)
 {
 
 JSONArray myoutJsonObject=JSONArray.fromObject(arr);

out.println(myoutJsonObject);
 
 
 }
 
 
 public void outarray(List <Volume> iwantList)
 
 {
 JSONArray jsonArray=JSONArray.fromObject(iwantList);  
 
 out.println(jsonArray);
  
 
 }
 
public void outarray(Volume [] iwantList)
 
 {
 JSONArray jsonArray=JSONArray.fromObject(iwantList);  
 
 out.println(jsonArray);
  
 
 }
 
 
 
 





}

0 0
原创粉丝点击