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

Android客户端和Struts交互Json数据

服务器端接收客户端发来的json对象,解析该json对象的数据后,再给客户端反送一个封装了新的数据的json对象?

Public class Action extends ActionSupport implements ServletRequestAware,ServletResponseAware{?

private String Json;?

private int age;?

private String name;?

private String password;?

private HttpServletRequest request;?

private HttpServletResponse response;?




public void execute()?

{?

try{?

JSONObject obj=new JSONObject(this.getJson())?

this.setAge(obj.getInt("age"));?

this.setName(obj.getString("name"));?

this.setPassword(obj.getString("password"));?




}catch(org.json.JSONException e)?

{?

e.printStack();?

}?

JSONObject object=new JSONObject();?

object.put("age",22);?

object.put("name",nikerlover);?

object.put("password",12345);?

JSONObject? tem=new JSONObject();//若需要传递数组,夹杂其他的杂项,可以用Map map=new HashMap<String,Object>()将数据封装好,创建List<Map<String,Object>>?

list=new ArrayList<Map<String,Object>>(),然后,list.add(map);再用JSONObject进行封装,JSONObject和JSONArray可以相互嵌套,你懂的?

JSONObject temp=new JSONObject();?

try{?

tem.put("user",object);?

temp.put("json",tem);?

response.setCharacterEncoding("UTF-8");?

response.getWriter().write(temp.toString());?

}catch(Exception e)?

{?

e.printStackTrace();?

}?

}?

// Getter and Setter method?

//public void setServletResponse(HttpServletResponse)?

}?




Android客户端:先给服务器发送一个封装好了的JSON对象,再等待服务器反送response对象,将response里的JSON对象获取并解析?

pubic void OnCreate(Handler instance)?

{?

String Url="http://59.64.34.45/project/index.action";?

HttpClient client=new DefaultHttpClient();?

HttpPost post=new HttpPost(url);?

List<NameValuePair> pair=new ArrayList<NameValuePair>()'?

try{?

JSONObject obj=new JSONObject();?

obj.put("age",2);?

obj.put("name",nikerlover);?

obj.put("password",45667);?

JSONObject json=new JSONObject();?

pair.add(new BasicValueNamePair("json",obj.toString()));?

post.setEntity(new UrlEncodedFormEntity(pair,HTTP.UTF_8));?

HttpResponse response=client.execute(post);?

if(response.getStatusLine().getStatusCode()==200)?

{?

String responseStr=EntityUtils.toString(response.getEntity());?

JSONObject json=new JSONObject(responseStr).getJSONObject("json");?

JSONObject object=json.getJSONObject("user");?


int Age=obj.getInt("age");?

String Name=obj.getString("name");?

String Password=obj.getString("password");?


}?

}?

}?