Mexican 2011-10-12
前阵子开发利用框架的服务器和Android机客户端的CS架构的程序,用到了JSON进行数据的传递,感觉JSON在获取出传递的数据方面还是很方便的,网上没有比较好的案例,先将服务器和客户端如何用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");
}
}
}