Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 【Android基礎知識】網絡操作:Json生成與解析

【Android基礎知識】網絡操作:Json生成與解析

編輯:關於Android編程

簡介

這裡主要介紹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 list;
	public int getResult() {
		return result;
	}
	public void setResult(int result) {
		this.result = result;
	}
	public List getList() {
		return list;
	}
	public void setList(List list) {
		this.list = list;
	}
}
Person.java
public class Person {
	private String name;
	private int age;
	private String url;
	
	private List schoolInfo = new ArrayList();

	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 getSchoolInfo() {
		return schoolInfo;
	}

	public void setSchoolInfo(List 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. 

	 *
	 * 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. 

	 *
	 * 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 lists = new ArrayList();
		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 schoolInfos = new ArrayList();
		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 schoolInfos2 = new ArrayList();
		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 schoolInfos3 = new ArrayList();
		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 schoolInfos4 = new ArrayList();
		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字符串並下載圖片 主界面為一個listView,其自定義布局為 item.xml


    
    
    
        
        
        
        
    

ListView 的適配器類 JsonAdapter.java類
public class JsonAdapter extends BaseAdapter{
	private List 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 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 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 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 parseJson(String json){
		try {
			JSONObject object = new JSONObject(json);
			int result = object.getInt("result");
			if(result == 1){
				//獲取一個json對象數組
				JSONArray  personArray = object.getJSONArray("list");
				List persons = new ArrayList();
				//遍歷數組,繼續解析
				for(int i = 0;i infos = new ArrayList();
					for(int j = 0 ;j從網絡獲取圖片並顯示在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();
    }
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved