前陣子開發利用框架的服務器和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");
}
}
}