您的位置:首页 > 理论基础 > 计算机网络

【Android基础知识】网络操作:Json生成与解析

2016-07-20 13:58 531 查看

简介

这里主要介绍Android生成一个Json格式的字符串,客户端通过网络获取服务器端生成的Json字符串进行解析,根据解析出来的Url去网络获取图片并显示在ListView中。最终实现效果如下



Json字符串为

{
"result": 1,
"list": [
{
"name": "nate",
"age": 12,
"url": "http://imgst-dl.meilishuo.net/pic/_o/84/a4/a30be77c4ca62cd87156da202faf_1440_900.jpg",
"schoolInfo": [
{
"schoolName": "清華"
},
{
"schoolName": "北大"
}
]
},
{
"name": "cat",
"age": 22,
"url": "http://s2.nuomi.bdimg.com/upload/deal/2014/1/V_L/623682-1391756281052.jpg",
"schoolInfo": [
{
"schoolName": "新东方"
},
{
"schoolName": "蓝翔"
}
]
},
{
"name": "cat",
"age": 22,
"url": "http://www.33lc.com/article/UploadPic/2012-8/201282413335761587.jpg",
"schoolInfo": [
{
"schoolName": "武当"
},
{
"schoolName": "峨眉"
}
]
},
{
"name": "jack",
"age": 12,
"url": "http://imgst-dl.meilishuo.net/pic/_o/84/a4/a30be77c4ca62cd87156da202faf_1440_900.jpg",
"schoolInfo": [
{
"schoolName": "清華"
},
{
"schoolName": "北大"
}
]
}
]
}

服务器端生成Json字符串

生成Json字符串,首先需要建立几个类
Result.java
public class Result {
private int result;
private List<Person> list;
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public List<Person> getList() {
return list;
}
public void setList(List<Person> list) {
this.list = list;
}
}
Person.java
public class Person {
private String name;
private int age;
private String url;

private List<SchoolInfo> schoolInfo = new ArrayList<SchoolInfo>();

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public List<SchoolInfo> getSchoolInfo() {
return schoolInfo;
}

public void setSchoolInfo(List<SchoolInfo> schoolInfo) {
this.schoolInfo = schoolInfo;
}

}
SchoolInfo.java
public class SchoolInfo {
private String schoolName;

public String getSchoolName() {
return schoolName;
}

public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}

}
JsonServlet.java 生成Json字符串(这里需要用到Gson.jar包)
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

this.doPost(request, response);
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();

Result result = new Result();
result.setResult(1);
List<Person> lists = new ArrayList<Person>();
result.setList(lists);

Person person1 = new Person();
person1.setName("nate");
person1.setAge(12);
person1.setUrl("http://imgst-dl.meilishuo.net/pic/_o/84/a4/a30be77c4ca62cd87156da202faf_1440_900.jpg");
List<SchoolInfo> schoolInfos = new ArrayList<SchoolInfo>();
SchoolInfo schoolInfo1 = new SchoolInfo();
schoolInfo1.setSchoolName("清華");
SchoolInfo schoolInfo2 = new SchoolInfo();
schoolInfo2.setSchoolName("北大");
schoolInfos.add(schoolInfo1);
schoolInfos.add(schoolInfo2);
person1.setSchoolInfo(schoolInfos);
lists.add(person1);

Person person2 = new Person();
person2.setName("cat");
person2.setAge(22);
person2.setUrl("http://s2.nuomi.bdimg.com/upload/deal/2014/1/V_L/623682-1391756281052.jpg");
List<SchoolInfo> schoolInfos2 = new ArrayList<SchoolInfo>();
SchoolInfo schoolInfo3 = new SchoolInfo();
schoolInfo3.setSchoolName("新东方");
SchoolInfo schoolInfo4 = new SchoolInfo();
schoolInfo4.setSchoolName("蓝翔");
schoolInfos2.add(schoolInfo3);
schoolInfos2.add(schoolInfo4);
person2.setSchoolInfo(schoolInfos2);
lists.add(person2);

Person person3 = new Person();
person3.setName("cat");
person3.setAge(22);
person3.setUrl("http://www.33lc.com/article/UploadPic/2012-8/201282413335761587.jpg");
List<SchoolInfo> schoolInfos3 = new ArrayList<SchoolInfo>();
SchoolInfo schoolInfo5 = new SchoolInfo();
schoolInfo5.setSchoolName("武当");
SchoolInfo schoolInfo6 = new SchoolInfo();
schoolInfo6.setSchoolName("峨眉");
schoolInfos3.add(schoolInfo5);
schoolInfos3.add(schoolInfo6);
person3.setSchoolInfo(schoolInfos3);
lists.add(person3);

Person person4 = new Person();
person4.setName("jack");
person4.setAge(12);
person4.setUrl("http://imgst-dl.meilishuo.net/pic/_o/84/a4/a30be77c4ca62cd87156da202faf_1440_900.jpg");
List<SchoolInfo> schoolInfos4 = new ArrayList<SchoolInfo>();
SchoolInfo schoolInfo7 = new SchoolInfo();
schoolInfo7.setSchoolName("清華");
SchoolInfo schoolInfo8 = new SchoolInfo();
schoolInfo8.setSchoolName("北大");
schoolInfos4.add(schoolInfo7);
schoolInfos4.add(schoolInfo8);
person4.setSchoolInfo(schoolInfos);
lists.add(person4);

Gson gson = new Gson();
System.out.println(gson.toJson(result));
//返回Json给客户端
out.print(gson.toJson(result));

}
客户端解析Json字符
4000
串并下载图片
主界面为一个listView,其自定义布局为 item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageView
android:id="@+id/imageview"
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"/>
<LinearLayout
android:layout_toRightOf="@+id/imageview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/school1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"/>
<TextView
android:id="@+id/school2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"/>
</LinearLayout>
</RelativeLayout>
ListView 的适配器类 JsonAdapter.java类
public class JsonAdapter extends BaseAdapter{
private List<Person> list;

private Context mContext;
private LayoutInflater inflater;
private Handler handler = new Handler();

public JsonAdapter(Context context){
this.mContext = context;
inflater = LayoutInflater.from(mContext);
}

public void setData(List<Person> data){
this.list = data;
}
@Override
public int getCount() {
return list.size();
}

@Override
public Object getItem(int position) {
return list.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = null;
if(convertView == null){
convertView = inflater.inflate(R.layout.item, null);
holder = new Holder(convertView);
convertView.setTag(holder);
}else{
holder = (Holder)convertView.getTag();
}
Person person = list.get(position);
holder.name.setText(person.getName());
holder.age.setText(""+person.getAge());//这里age是int型,如果不改成string的话会报找不到资源错误

List<SchoolInfo> schoolInfos = person.getSchoolInfo();
SchoolInfo schoolInfo1 = schoolInfos.get(0);
SchoolInfo schoolInfo2 = schoolInfos.get(1);

holder.school1.setText(schoolInfo1.getSchoolName());
holder.school2.setText(schoolInfo2.getSchoolName());
//通过获取到的url去网络获取图片并使用handler显示在界面上
new HttpImages(holder.imageView, handler, person.getUrl()).start();
return convertView;
}
class Holder{
private ImageView imageView;
private TextView name;
private TextView age;
private TextView school1;
private TextView school2;
public Holder(View  view){
imageView = (ImageView)view.findViewById(R.id.imageview);
name = (TextView)view.findViewById(R.id.name);
age = (TextView)view.findViewById(R.id.age);
school1 = (TextView)view.findViewById(R.id.school1);
school2 = (TextView)view.findViewById(R.id.school2);
}
}
}
访问网络获取JSon并解析Json类 JsonHttpJson.java
public class JsonHttpJson extends Thread{
private String url;
private ListView listView;
private Context context;
private JsonAdapter adapter;
private Handler handler;
public JsonHttpJson(String url,Context context,ListView listView,JsonAdapter adapter,Handler handler){
this.url = url;
this.context = context;
this.listView = listView;
this.adapter = adapter;
this.handler = handler;
}
@Override
public void run() {
URL httpUrl = null;
try {
//从服务器获取Json字符串
httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setReadTimeout(3000);
conn.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer buffer = new StringBuffer();
String str;
while((str= reader.readLine())!= null){
buffer.append(str);
}
//解析获取到的Json字符串,返回一个Person的集合
final List<Person> data = parseJson(buffer.toString());
handler.post(new Runnable() {

@Override
public void run() {
//设置数据源,设置适配器
adapter.setData(data);
listView.setAdapter(adapter);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//解析JSon
private List<Person> parseJson(String json){
try {
JSONObject object = new JSONObject(json);
int result = object.getInt("result");
if(result == 1){
//获取一个json对象数组
JSONArray  personArray = object.getJSONArray("list");
List<Person> persons = new ArrayList<Person>();
//遍历数组,继续解析
for(int i = 0;i<personArray.length();i++){
Person personM = new Person();
JSONObject person = personArray.getJSONObject(i);
String name = person.getString("name");
int age = person.getInt("age");
String url = person.getString("url");
personM.setAge(age);
personM.setName(name);
personM.setUrl(url);
//schoolInfos为一个数组,继续进行for循环解析
JSONArray schoolInfos = person.getJSONArray("schoolInfo");
List<SchoolInfo> infos = new ArrayList<SchoolInfo>();
for(int j = 0 ;j<schoolInfos.length();j++){
SchoolInfo info = new SchoolInfo();
JSONObject school = schoolInfos.getJSONObject(j);
String schoolName = school.getString("schoolName");
info.setSchoolName(schoolName);
infos.add(info);
}
personM.setSchoolInfo(infos);
//把解析出的对象加入到list中
persons.add(personM);
}
return persons;
}else{
Toast.makeText(context, "json error", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
从网络获取图片并显示在ImageView上的类 HttpImages.java
public class HttpImages extends Thread{
private ImageView imageView;
private Handler handler;
private String url;

public HttpImages(ImageView imageView,Handler handler,String url){
this.imageView = imageView;
this.handler = handler;
this.url = url;
}
@Override
public void run() {
URL httpUrl;
try {
httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setReadTimeout(3000);
conn.setRequestMethod("GET");
//获取输入流
InputStream in = conn.getInputStream();
//解析输入流获取图片
final Bitmap bitmap = BitmapFactory.decodeStream(in);
//使用handler 更新界面
handler.post(new Runnable() {

@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
主类,调用类:MainActivity.java
public class MainActivity extends Activity {
private ListView listView;
private JsonAdapter adapter;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listview);
adapter = new JsonAdapter(this);
String url = "http://192.168.199.126:8080/Server/JsonServlet";
new JsonHttpJson(url, this,listView,adapter,handler).start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息