欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android 之 JSON的使用用法

程序员文章站 2022-05-16 16:44:10
...
1、 生活中,各大公司会提供公共的API供程序访问数据,通过调用API , 一般返回的数据有两种格式:
xml格式;json格式;

2、JSON:
* 概念:是一种轻量级的数据交换格式;采用的是完全独立于语言的文本格式;

3、json数据格式分类:
* key-values 格式; {name:"mike",age : 18}
* 对象格式; {{name:"mike",age : 18},{name:"mike2",age : 19}}   注意:{} 为对象;
* 数组格式:{name:["","",""],age:38}              注意:[] 表示的是数组;
* 数组中包含对象:{students:[{},{}],age:33}

小贴士:万事万物皆对象;

3、将数据以JSON 的格式实现:案例如下

java代码:
 package com.example.json_parse;

import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EncodingUtils;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Xml.Encoding;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JsPromptResult;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	private Button parseJSON,achieveJSON;
	private EditText show;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		/* 组件对象 */
		parseJSON = (Button) findViewById(R.id.parseJSON);
		achieveJSON = (Button) findViewById(R.id.achieveJSON);
		show = (EditText) findViewById(R.id.show);
		
		/* 设置事件监听器:将数据用JSON格式表示 */
		achieveJSON.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				achieve_JSON();
			}
		});
		
		/* 设置事件监听器:解析JSON */
		parseJSON.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				parse_JSON();
			}
		});
		
		
	}
	
	/* 解析JSON格式文本为字符串 */
	protected void parse_JSON(){
		try{
			/* 首先获取服务器返回的JSON文件信息,保存在一个jsp页面中 */
			String path ="http://192.168.16.16:8080/index1.jsp";
			
			/* 设置访问方式;并通过IP地址访问服务器 */
			HttpGet httpGet = new HttpGet(path);
			
			/* 发送请求 */
			HttpClient httpClient = new DefaultHttpClient();
			HttpResponse httpResponse = httpClient.execute(httpGet);
			
			/* 上述请求发送到服务器后会返回请求码,可以用来判断是否请求成功,200代表成功 */
			if(httpResponse.getStatusLine().getStatusCode()==200){
				Toast.makeText(MainActivity.this, "请求成功!", 1000).show();
				
				HttpEntity httpEntity = httpResponse.getEntity();

				/* 获取数据:工具类EntityUtils , 能将得到的数据转换为字符串 */
				String info = EntityUtils.toString(httpEntity, "UTF-8");
				
				
				/* 对字符串操作:将字符串转换为 JSONObject 对象 */
				JSONObject person = new JSONObject(info);
					
				
				/**********************************************************************/
				/* key==students 的值 */
				JSONObject students_value = (JSONObject) person.get("students");
				/* key==school的值 */
				
				String school_value = EncodingUtils.getString(person.getString("school").getBytes(),"GBK") ;
				
				/**********************************************************************/
				
				/**********************************************************************/
				/* 在key==students 的值中,key==c1 的值 *//* key==c2 的值 */
				JSONObject students_c1_value = students_value.getJSONObject("c1");
				JSONObject students_c2_value = students_value.getJSONObject("c2");
				/**********************************************************************/
				
				/**********************************************************************/
				/* 在key==students ,key==c1 中,并且:key==class / number /detail */
				String c1_class_value = students_c1_value.getString("class");
				String c1_number_value = students_c1_value.getString("number");
				JSONArray detail_value = students_c1_value.getJSONArray("detail");
				
				/* 处理detail数组中的元素 */
				String c1_detail_name_value = "";
				String c1_detail_age_value = "";
				ArrayList<String> c1_detail_list = new ArrayList<String>();
				for(int i=0;i<detail_value.length();i++){
					JSONObject detail_value_item = detail_value.getJSONObject(i);
					c1_detail_name_value = detail_value_item.getString("name");
					c1_detail_age_value = detail_value_item.getString("age");
					c1_detail_list.add(c1_detail_name_value+" "+c1_detail_age_value);
				}
				/**********************************************************************/
				
				
				/**********************************************************************/
				/* key==student ,key==c2中,并且:key=class /number/detail */
				String c2_class_value = students_c2_value.getString("class");
				String c2_number_value = students_c2_value.getString("number");
				JSONArray c2_detail_value = students_c2_value.getJSONArray("detail");
				
				/* 处理detail数组中的元素 */
				
				ArrayList<String> c2_detail_list = new ArrayList<String>();
				for(int i=0;i<detail_value.length();i++){
					JSONObject detail_value_item = detail_value.getJSONObject(i);
					String c2_detail_name_value = detail_value_item.getString("name");
					String c2_detail_age_value = detail_value_item.getString("age");
					c2_detail_list.add(c2_detail_name_value+" "+c2_detail_age_value);
				}
				/**********************************************************************/
				
				/* 输出信息 */
				for(int i=0;i<c1_detail_list.size();i++){
					Toast.makeText(MainActivity.this, c1_class_value+"\n"+c1_number_value+"\n"+c1_detail_list.get(i)+"\n"+school_value, 
							1000).show();
				}
				for(int i=0;i<c2_detail_list.size();i++){
					Toast.makeText(MainActivity.this, c2_class_value+"\n"+c2_number_value+"\n"+c2_detail_list.get(i)+"\n"+school_value, 
							1000).show();
				}
				
			}else{
				Toast.makeText(MainActivity.this, "服务器访问失败!", 1000).show();
			}
			
		}catch(Exception ex){
			ex.printStackTrace();
			Toast.makeText(MainActivity.this, "出现异常了!", 1000).show();
		}
		
	}

	/* 将数据以JSON 的格式表示  */
	protected void achieve_JSON(){
//		{
//		students:
//			{
//				c1:{class:"android1",number:37,detail:[{name:"aa",age:18},{name:"ff",age:19}]},
//				c2:{class:"android2",number:38,detail:[{name:"hh",age:16}{name:"kk",age:19}]},
//				
//			},
//		school:"国土地信学院"
//		}
		try{
			
			/* 对上述的格式表示:从最小的级别进行推导 *//* 按如下导论进行格式转换设置 */
			
			/* detail:[{name:"aa",age:18},{name:"ff",age:19}] */
			JSONArray detail_jsonArr = new JSONArray();
			/* 数组中的元素1 */
			JSONObject detail_json_arr_item = new JSONObject();
			detail_json_arr_item.put("name", "aa");
			detail_json_arr_item.put("age", 18);
			/* 数组中的元素2 */
			JSONObject detail_json_arr_item2 = new JSONObject();
			detail_json_arr_item2.put("name", "ff");
			detail_json_arr_item2.put("age", 19);
			detail_jsonArr.put(detail_json_arr_item);
			detail_jsonArr.put(detail_json_arr_item2);
			
			
			/* c1:{class:"android1",number:37,detail:[{name:"aa",age:18},{name:"ff",age:19}]} */
			JSONObject c1_jsonObject = new JSONObject();
			c1_jsonObject.put("class", "android1");
			c1_jsonObject.put("number", 37);
			c1_jsonObject.put("detail", detail_jsonArr);
			
			
			
			/* detail:[{name:"hh",age:16},{name:"kk",age:19}] */
			JSONArray c2_detail_jsonArr = new JSONArray();
			/* 数组中的元素1 */
			JSONObject c2_detail_json_arr_item = new JSONObject();
			c2_detail_json_arr_item.put("name", "bb");
			c2_detail_json_arr_item.put("age", 38);
			/* 数组中的元素2 */
			JSONObject c2_detail_json_arr_item2 = new JSONObject();
			c2_detail_json_arr_item2.put("name", "cc");
			c2_detail_json_arr_item2.put("age", 49);
			
			/* 将元素添加到数组 */
			c2_detail_jsonArr.put(c2_detail_json_arr_item);
			c2_detail_jsonArr.put(c2_detail_json_arr_item2);
			
			
			
			/* c2:{class:"android2",number:38,detail:[{name:"hh",age:16},{name:"kk",age:19}]} */
			JSONObject c2_jsonObject = new JSONObject();
			c2_jsonObject.put("class", "android2");
			c2_jsonObject.put("number", 38);
			c2_jsonObject.put("detail", c2_detail_jsonArr);
			
			
			/* students:{
		c1:{class:"android1",number:37,detail:[{name:"aa",age:18},{name:"ff",age:19}]},
		c2:{class:"android2",number:38,detail:[{name:"hh",age:16},{name:"kk",age:19}]}} */
			JSONObject students_json = new  JSONObject();
			students_json.put("c1", c1_jsonObject);
			students_json.put("c2", c2_jsonObject);
			
			/* 所有 */
			JSONObject person = new JSONObject();
			person.put("students", students_json);
			person.put("school","湖北国土资源职业学院");
			show.setText(person.toString());
		}catch(Exception ex){
			
		}
		
		
	}


}
相关标签: json android