JSON有两种表示结构,对象和数组.
对象结构以”{”大括号开始,以”}”大括号结束。中间部分由0或多个以”,”分隔的”key(关键字)/value(值)”对构成,关键字和值之间以”:”分隔,语法结构如代码。
其中关键字是字符串,而值可以是字符串,数值,true,false,null,对象或数组
数组结构以”[”开始,”]”结束。中间由0或多个以”,”分隔的值列表组成,语法结构如代码。
****************************************************案例*******************************************
这里先贴出bean类
Result
package com.lw.bean; import java.util.ArrayList; import java.util.List; public class Result { //结果值,如果为2说明返回正确 private int result; private List<Person> personData = new ArrayList<Person>(); public int getResult() { return result; } public void setResult(int result) { this.result = result; } public List<Person> getPersonData() { return personData; } public void setPersonData(List<Person> personData) { this.personData = personData; } }
Person
package com.lw.bean; import java.util.List; public class Person { private String url; private String name; private int age; private List<SchoolInfo> schoolInfo; public List<SchoolInfo> getSchoolInfo() { return schoolInfo; } public void setSchoolInfo(List<SchoolInfo> schoolInfo) { this.schoolInfo = 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; } }
SchoolInfo
package com.lw.bean; public class SchoolInfo { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
接下来贴出主界面布局和Listview中的每个item的布局文件
json.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/imageView" android:layout_width="150dp" android:layout_height="100dp" android:layout_alignParentLeft="true" /> <RelativeLayout android:layout_width="fill_parent" android:layout_height="100dp" android:layout_toRightOf="@id/imageView" android:padding="10dp" > <TextView android:id="@+id/name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="name" /> <TextView android:id="@+id/age" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/name" android:text="age" /> <TextView android:id="@+id/school1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/age" android:text="school1" android:textSize="20dp" /> <TextView android:id="@+id/school2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/school1" android:text="school2" android:textSize="20dp" /> </RelativeLayout> </RelativeLayout>
接下来贴出主activity
JsonActivyty
package com.lw.http01; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.widget.ListView; public class JsonActivyty extends Activity { private ListView listView; private JsonAdapter jsonAdapter; private Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /** json布局文件中,只有一个listview控件 */ setContentView(R.layout.json); listView = (ListView) findViewById(R.id.listView); /** * 一开始是没有数据的,后来从服务器获取在子线程中跟新数据和ui界面的 * */ jsonAdapter = new JsonAdapter(this); /** * 服务度http://192.168.79.101:8080/testAndroidServer/jsonServlet就能获取到json数据 * 这里没有贴出服务端代码,知道上面一句话就够了 */ new JsonThread( "http://192.168.79.101:8080/testAndroidServer/jsonServlet", this, listView, jsonAdapter, handler).start(); } }
接下来循序渐进先贴出
JsonThread
package com.lw.http01; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.os.Handler; import android.widget.ListView; import android.widget.Toast; import com.lw.bean.Person; import com.lw.bean.SchoolInfo; public class JsonThread extends Thread { /** * url是服务器地址 * context是环境,需要toast提示 * listview是需要setadapter的设置适配器 * jsonAdapter是需要设置数据的 * handler是需要子线程更新ui的 */ private String url; private Context context; private ListView listView; private JsonAdapter jsonAdapter; private Handler handler; public JsonThread(String url, Context context, ListView listView, JsonAdapter jsonAdapter, Handler handler) { this.url = url; this.context = context; this.listView = listView; this.jsonAdapter = jsonAdapter; this.handler = handler; } @Override public void run() { try { // 创建URL对象,并且设置相应的参数 URL httpurl = new URL(url); //打开连接 HttpURLConnection conn = (HttpURLConnection) httpurl .openConnection(); conn.setReadTimeout(5000); conn.setRequestMethod("GET"); // 从服务器读取数据,需要读入流 BufferedReader reader = new BufferedReader(new InputStreamReader( conn.getInputStream())); // 读取完毕,就存放到StringBuffer容器中 StringBuffer sb = new StringBuffer(); String str = ""; while ((str = reader.readLine()) != null) { // 当读取完毕,就添加到容器中 sb.append(str); } // 将读取到的Json字符串,进行解析为Person对象集合 final List<Person> parseJson = parseJson(sb.toString()); // handler在子线程中更新数据 handler.post(new Runnable() { @Override public void run() { // 设置数据到adapter视图中,使其获取到数据 jsonAdapter.setData(parseJson); // 设置适配器 listView.setAdapter(jsonAdapter); } }); } catch (Exception e) { e.printStackTrace(); } } /*** * 解析服务端返回的Json字符串数据,因为adapter的视图中item是一个个Person对象,所以返回Person集合即可 * 这里用android的原生解析 */ private List<Person> parseJson(String json) { //json解析完毕,返回person的集合对象 List<Person> persons = new ArrayList<Person>(); try { /** * {"1":[{person对象},{person对象},{person对象}]} * 所以整体是个json对象,而不是json数组 * 所以创建JSONObject对象 */ JSONObject jsonObj = new JSONObject(json); //获取result值 int result = jsonObj.getInt("result"); //如果为2说明返回正确 if (result == 2) { //获取person的json数组 JSONArray personData = jsonObj.getJSONArray("personData"); /** * 循环解析每一个person对象 */ for (int i = 0; i < personData.length(); i++) { //创建person对象 Person personObj = new Person(); List<SchoolInfo> scInfos = new ArrayList<SchoolInfo>(); //从json对象数组中获取每一个json类型的person对象 JSONObject person = personData.getJSONObject(i); //为person对象设置json类型的person对象的值 personObj.setName(person.getString("name")); personObj.setAge(person.getInt("age")); personObj.setUrl(person.getString("url")); /**获取json类型的person中的school信息*/ JSONArray scs = person.getJSONArray("schoolInfo"); for (int j = 0; j < scs.length(); j++) { SchoolInfo schoolObj = new SchoolInfo(); JSONObject school = scs.getJSONObject(j); schoolObj.setName(school.getString("name")); scInfos.add(schoolObj); } personObj.setSchoolInfo(scInfos); persons.add(personObj); } } else { Toast.makeText(context, "error", 1); } } catch (JSONException e) { e.printStackTrace(); } return persons; } }
接下来贴出适配器的代码
JsonAdapter
package com.lw.http01; import java.util.List; import android.content.Context; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.lw.bean.Person; import com.lw.bean.SchoolInfo; public class JsonAdapter extends BaseAdapter { private List<Person> list; private Context context; private LayoutInflater inflater; private Handler handler = new Handler(); public JsonAdapter(Context context) { this.context = context; inflater = LayoutInflater.from(context); } public JsonAdapter(List<Person> list, Context context) { this.list = list; this.context = context; inflater = LayoutInflater.from(context); } /** * 设置数据的,数据是从服务器解析过来的 * @param list */ public void setData(List<Person> list){ this.list = list; } @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) { ViewHolder holder = null; if (convertView == null) { convertView = inflater.inflate(R.layout.item, null); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } /*** * item的数据是从setData中得来的,是jsonThread中handler操作的 */ Person person = list.get(position); holder.name.setText(person.getName()); holder.age.setText(person.getAge()+""); List<SchoolInfo> scs = person.getSchoolInfo(); holder.school1.setText(scs.get(0).getName()); holder.school2.setText(scs.get(1).getName()); //这里的图片信息,也是需要开启子线程,进行获取,需要传递这3个参数 new HttpImage(holder.imageView, person.getUrl(), handler).start(); return convertView; } /** * viewHodler不解释 * */ class ViewHolder { private TextView name; private TextView age; private TextView school1; private TextView school2; private ImageView imageView; public ViewHolder(View view) { 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); imageView = (ImageView) view.findViewById(R.id.imageView); } } }
接下来图片获取的线程
HttpImage
package com.lw.http01; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.widget.ImageView; public class HttpImage extends Thread { /** * imageview是需要在分线程中handler更新ui的 * url是图片的url * handler是子线程跟新ui操作的 */ private ImageView imageView; private String url; private Handler handler; public HttpImage(ImageView imageView, String url, Handler handler) { this.imageView = imageView; this.url = url; this.handler = handler; } @Override public void run() { try { /** * 跟jsonThread操作一样,系列的参数 */ URL httpurl = new URL(url); HttpURLConnection conn = (HttpURLConnection) httpurl.openConnection(); conn.setReadTimeout(5000); conn.setRequestMethod("GET"); //这样的方式也可以获取一个图片 decodeStream final Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream()); handler.post(new Runnable() { @Override public void run() { //子线程中直接更新界面 imageView.setImageBitmap(bitmap); } }); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-05 05:29:15