您的位置:首页 > 移动开发 > Android开发

Android学习笔记:用JSON封装JavaBean传输

2014-03-19 21:04 381 查看
本次笔记本人重点如下:

1.如何将JavaBean转化成JSONObject +JSONObject转化成JSONArray+JSONArray转化成JSONObject乃至JavaBean

2.复习适配器的调用以及显示

3.在httppost的setEntity方法中添加UTF-8编码 防止发生客户端传送中文乱码的情况。

1.效果:

 1-1.Android端



输入数据之后 点击添加 添加一条信息在Student数组中

当点击发送按钮 将Student数组转化成JSONArray发送到服务器端

服务器端原封不动╮( ̄⊿ ̄")╭ 为什么原封不动呢,因为发送到服务器之后 服务器将JSONArray解析成JSONObject 再转化成JavaBean形式 最后发回来也还是JSON格式,所以只是作一个JSONArray传输的样子 进行数据传输而已,在本次实验上没有实际的网络传输意图。

然后点击 显示提交结果的按钮 ListView根据服务器发送的JSONArray数据进行LIstView的更新。

实际代码:

1.整体架构



2.Android界面代码

<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Main" >

<TextView
android:id="@+id/TV_Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="18dp"
android:layout_marginTop="25dp"
android:text="@string/StringName" />

<EditText
android:id="@+id/ET_Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/TV_Name"
android:layout_alignBottom="@+id/TV_Name"
android:layout_alignParentRight="true"
android:layout_toRightOf="@+id/TV_Name"
android:ems="10"
android:inputType="text" />

<TextView
android:id="@+id/TV_Id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/TV_Name"
android:layout_below="@+id/ET_Name"
android:layout_marginTop="23dp"
android:text="@string/StringId" />

<EditText
android:id="@+id/ET_Id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/TV_Id"
android:layout_alignBottom="@+id/TV_Id"
android:layout_alignRight="@+id/ET_Name"
android:layout_toRightOf="@+id/TV_Id"
android:ems="10"
android:inputType="number" >

<requestFocus />
</EditText>

<TextView
android:id="@+id/TV_Sex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ET_Id"
android:layout_marginTop="20dp"
android:layout_toLeftOf="@+id/ET_Id"
android:text="@string/StringSex" />

<RadioGroup
android:id="@+id/RDG_Sex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/ET_Id"
android:layout_alignTop="@+id/TV_Sex"
android:orientation="horizontal" >

<RadioButton
android:id="@+id/RD_Man"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="19dp"
android:checked="true"
android:text="@string/StringMan" />

<RadioButton
android:id="@+id/RD_Woman"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="53dp"
android:text="@string/StringWoman" />
</RadioGroup>

<Button
android:id="@+id/BT_Send"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/BT_Get"
android:layout_below="@+id/RDG_Sex"
android:layout_marginTop="26dp"
android:text="@string/StringSend" />

<Button
android:id="@+id/BT_Clear"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:layout_above="@+id/BT_Get"
android:layout_alignRight="@+id/BT_Get"
android:text="@string/StringClear" />

<Button
android:id="@+id/BT_Get"
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/ET_Id"
android:layout_below="@+id/BT_Send"
android:text="@string/StringGet" />

<LinearLayout
android:id="@+id/LO_Result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignLeft="@+id/BT_Get"
android:layout_below="@+id/BT_Get"
android:orientation="vertical" >

<ListView
android:id="@+id/LV_Student"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>

</LinearLayout>

<Button
android:id="@+id/BT_Add"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/BT_Clear"
android:layout_alignRight="@+id/BT_Clear"
android:layout_alignTop="@+id/RDG_Sex"
android:layout_toRightOf="@+id/RDG_Sex"
android:text="@string/StringAdd" />

</RelativeLayout>

3.Android端代码

用的时候记得改ip地址

Main.java

package bnuz.alt.pojosend;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import bnuz.alt.pojo.Student;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class Main extends Activity {

private EditText ET_Name, ET_Id;
private Button BT_Send, BT_Clear, BT_Get, BT_Add;
private RadioGroup RDG_Sex;
private RadioButton Man, Woman;
private String Sex;
private ListView LV_Student;
private JSONArray L_Student;
private static final String ServerAddress = "http://113.103.149.27:8080/ServerJsonDemo/servlet/JsonServlet",
TAG = "ATag";
@SuppressWarnings("unused")
private List<Student> Students;
private ArrayList<String> InfoName ;
private ArrayAdapter<String> LV_Adapter;
private ArrayList<ArrayList<String>>Info;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ET_Name = (EditText) findViewById(R.id.ET_Name);
ET_Id = (EditText) findViewById(R.id.ET_Id);
BT_Send = (Button) findViewById(R.id.BT_Send);
BT_Clear = (Button) findViewById(R.id.BT_Clear);
BT_Get = (Button) findViewById(R.id.BT_Get);
BT_Add = (Button) findViewById(R.id.BT_Add);
RDG_Sex = (RadioGroup) findViewById(R.id.RDG_Sex);
Man = (RadioButton) findViewById(R.id.RD_Man);
Woman = (RadioButton) findViewById(R.id.RD_Woman);
Sex = "男";
LV_Student = (ListView) findViewById(R.id.LV_Student);
L_Student = new JSONArray();

/*为ListView添加适配器*/
Students=new ArrayList<Student>();
InfoName = new ArrayList<String>();
Info=new ArrayList<ArrayList<String>>();
LV_Adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1,InfoName );

/* 添加按钮清除方法 */
BT_Clear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ET_Name.setText("");
ET_Id.setText("");
}
});

/* 添加性别检测方法 */
RDG_Sex.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == Man.getId()) {
Sex = "男";
} else if (checkedId == Woman.getId()) {
Sex = "女";
}
}

});
/* 添加添加方法.. */
BT_Add.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (CheckInput()) {
String InputName = ET_Name.getText().toString();
int InputId = Integer.parseInt((ET_Id.getText().toString()));
/* 将信息转化为JSONObject */
Student studentmsg = new Student(InputId, InputName, Sex);
JSONObject stuJsonObj = studentmsg.toJSONObj();
L_Student.put(stuJsonObj);
Log.d(TAG, L_Student.toString());
Toast.makeText(Main.this, "添加成功", Toast.LENGTH_LONG).show();
ET_Name.setText("");
ET_Id.setText("");
}
}

});
/* 添加按钮发送方法 */
BT_Send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
JSONOperation sendJsonTask = new JSONOperation();
Log.d(TAG, L_Student.toString());

sendJsonTask.execute(L_Student);
}

});

/* 添加信息显示 */
BT_Get.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LV_Adapter = new ArrayAdapter<String>(Main.this, android.R.layout.simple_list_item_1, InfoName);
LV_Student.setAdapter(LV_Adapter);
LV_Student.setOnItemClickListener(new OnItemClickListener(){
@SuppressLint("ShowToast")
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {

Toast toast=Toast.makeText(getBaseContext(),""+Info.get(arg2), 1000);
toast.show();
}

});
}

});
}

/* 检测输入 */
public boolean CheckInput() {
if (!ET_Id.getText().toString().equals("")
&& !ET_Name.getText().toString().equals(""))
return true;
else {
Toast.makeText(Main.this, "请输入姓名和学号", Toast.LENGTH_SHORT).show();
return false;
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.main, menu);
return true;
}

public class JSONOperation extends AsyncTask<JSONArray, Void, String> {

@Override
protected String doInBackground(JSONArray... JSONObjs) {
String Result_Show = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(ServerAddress);
Log.d(TAG, "" + (JSONObjs[0].length()));
try {
httppost.setEntity(new StringEntity(JSONObjs[0].toString(),
"UTF-8"));

Log.d(TAG, EntityUtils.toString(httppost.getEntity()));
HttpResponse httpres = httpclient.execute(httppost);

if (httpres.getStatusLine().getStatusCode() == 200) {
Log.d(TAG, "成功连接信号");
String Res = EntityUtils.toString(httpres.getEntity(),
"UTF-8");
JSONArray JsonResult = new JSONArray(Res);
Result_Show = JsonResult.toString();
Log.d(TAG, Result_Show);

/*为Info添加信息*/
for(int i=0;i< JsonResult.length();i++){
JSONObject jsonObj=JsonResult.getJSONObject(i);
ArrayList<String> SubInfo = new ArrayList<String>();
String SName = jsonObj.getString("name");
String SId = jsonObj.getString("id");
String SSex = jsonObj.getString("sex");
SubInfo.add(SId);
SubInfo.add(SSex);
InfoName.add(SName);
Info.add(SubInfo);
}
}

} catch (Exception e) {
Log.d(TAG, e.toString());
}
return Result_Show;
}

@Override
protected void onPostExecute(String result) {

super.onPostExecute(result);

}
}
}


Student.java-Android与Servlet端公用
package bnuz.alt.pojo;

import org.json.JSONObject;

public class Student {
private int id;
private String name;
private String sex;

public Student(){
this.id=-1;
this.name="默认作者:Aquariuslt";
this.sex="男";
}
public Student(int id,String name,String sex){
this.id=id;
this.name=name;
this.sex=sex;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public JSONObject toJSONObj(){
JSONObject stuJsonObj = new JSONObject();
try{
stuJsonObj.put("id", this.id);
stuJsonObj.put("name", this.name);
stuJsonObj.put("sex",this.sex );
}catch(Exception e){
e.printStackTrace();
}
return stuJsonObj;

}
}


4.Servlet端
package com.jsondemo.servlet;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

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

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

@SuppressWarnings({ "serial", "unused" })
public class JsonServlet extends HttpServlet {

public JsonServlet() {
super();
}

public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/json;charset=UTF-8");
StringBuffer sb = new StringBuffer("");
String result = "";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
request.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
sb.append(temp);
}
br.close();
result = sb.toString();
// 打印android端上传的JSON数据
//System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}

JSONArray jsonArray=JSONArray.fromObject(result);
System.out.println("JSONArray大小:"+jsonArray.size());
for(int i=0;i<jsonArray.size();i++){
JSONObject jsonobj=jsonArray.getJSONObject(i);
System.out.println(jsonobj.toString());
}
PrintWriter pw = response.getWriter(); // 封装服务器返回的JSON对象 JSONObject
pw.write(result);
pw.flush();
pw.close();

}

public void init() throws ServletException {
// Put your code here
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息