Android客户端和Struts交互Json数据

如竹 2012-05-02

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

PublicclassActionextendsActionSupportimplementsServletRequestAware,ServletResponseAware{

privateStringJson;

privateintage;

privateStringname;

privateStringpassword;

privateHttpServletRequestrequest;

privateHttpServletResponseresponse;

publicvoidexecute()

{

try{

JSONObjectobj=newJSONObject(this.getJson())

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

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

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

}catch(org.json.JSONExceptione)

{

e.printStack();

}

JSONObjectobject=newJSONObject();

object.put("age",22);

object.put("name",nikerlover);

object.put("password",12345);

JSONObjecttem=newJSONObject();//若需要传递数组,夹杂其他的杂项,可以用Mapmap=newHashMap<String,Object>()将数据封装好,创建List<Map<String,Object>>

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

JSONObjecttemp=newJSONObject();

try{

tem.put("user",object);

temp.put("json",tem);

response.setCharacterEncoding("UTF-8");

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

}catch(Exceptione)

{

e.printStackTrace();

}

}

//GetterandSettermethod

//publicvoidsetServletResponse(HttpServletResponse)

}

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

pubicvoidOnCreate(Handlerinstance)

{

StringUrl="http://59.64.34.45/project/index.action";

HttpClientclient=newDefaultHttpClient();

HttpPostpost=newHttpPost(url);

List<NameValuePair>pair=newArrayList<NameValuePair>()'

try{

JSONObjectobj=newJSONObject();

obj.put("age",2);

obj.put("name",nikerlover);

obj.put("password",45667);

JSONObjectjson=newJSONObject();

pair.add(newBasicValueNamePair("json",obj.toString()));

post.setEntity(newUrlEncodedFormEntity(pair,HTTP.UTF_8));

HttpResponseresponse=client.execute(post);

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

{

StringresponseStr=EntityUtils.toString(response.getEntity());

JSONObjectjson=newJSONObject(responseStr).getJSONObject("json");

JSONObjectobject=json.getJSONObject("user");

intAge=obj.getInt("age");

StringName=obj.getString("name");

StringPassword=obj.getString("password");

}

}

}

相关推荐

大树 / 0评论 2011-09-29