一.Json数据类型:
1.Json_object类型(Json_object.txt):
{"name":"zhangsanfeng","age":3,"sex":"nv"}
2.Json_array类型(Json_array.txt):
[{"name":"zhangsanfeng","age":3,"sex":"nv"},{"name":"zhaobenshan","age":2,"sex":"renyao"}]
3.混合Json类型(Jsony.txt):
{
"resultcode": "200",
"reason": "查询成功!",
"result": {
"sk": {
"temp": "21",
"wind_direction": "西风",
"wind_strength": "2级",
"humidity": "4%",
"time": "14:25"
},
"today": {
"city": "天津",
"date_y": "2014年03月21日",
"week": "星期五",
"temperature": "8℃~20℃",
"weather": "晴转霾",
"weather_id": {
"fa": "00",
"fb": "53"
},
"wind": "西南风微风",
"dressing_index": "较冷",
"dressing_advice": "建议着大衣、呢外套加毛衣、卫衣等服装。",
"uv_index": "中等",
"comfort_index": "",
"wash_index": "较适宜",
"travel_index": "适宜",
"exercise_index": "较适宜",
"drying_index": ""
},
"future": [
{
"temperature": "28℃~36℃",
"weather": "晴转多云",
"weather_id": {
"fa": "00",
"fb": "01"
},
"wind": "南风3-4级",
"week": "星期一",
"date": "20140804"
},
{
"temperature": "28℃~36℃",
"weather": "晴转多云",
"weather_id": {
"fa": "00",
"fb": "01"
},
"wind": "东南风3-4级",
"week": "星期二",
"date": "20140805"
},
{
"temperature": "27℃~35℃",
"weather": "晴转多云",
"weather_id": {
"fa": "00",
"fb": "01"
},
"wind": "东南风3-4级",
"week": "星期三",
"date": "20140806"
},
{
"temperature": "27℃~34℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "东南风3-4级",
"week": "星期四",
"date": "20140807"
},
{
"temperature": "27℃~33℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "东北风4-5级",
"week": "星期五",
"date": "20140808"
},
{
"temperature": "26℃~33℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "北风4-5级",
"week": "星期六",
"date": "20140809"
},
{
"temperature": "26℃~33℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "北风4-5级",
"week": "星期日",
"date": "20140810"
}
]
},
"error_code": 0
}
一.原生解析(采用谷歌原生Json)
1.MainActivity.java文件
package com.ittujunyong.simplejson;
import org.json.Exception;
import org.json.JSONArray;import java.util.ArrayList;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.content.Context;
import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {protected static final int SUCCESS_object = 1;
protected static final int SUCCESS_array = 2;protected static final int SUCCESS_jsony = 3;protected static final int ERROR = 4;private TextView tv;private ListView lv; //使用到上下文的对象 private Context context = MainActivity.this;//定义路径private String url_object = "http://192.168.12.143:8080/json_object.txt"; private String url_array = "http://192.168.12.143:8080/json_array.txt";private String url_jsony = "http://192.168.12.143:8080/jsony.txt";//定义Handler private Handler handler = new Handler(){//重写方法public void handleMessage(android.os.Message msg) {//选择switch(msg.what){case SUCCESS_object: String jsonData = (String) msg.obj;//调用方法UserBean bean = readJsonObject(jsonData);//显示数据tv.setText(bean.toString());break;
case SUCCESS_array: String jsonData = (String) msg.obj; //调用方法解析JSON数据 ArrayList<UserBean> al = readJsonData(jsonData); //定义方法 MyAdapter adapter = new MyAdapter(context,al); //显示在ListView上面.设置适配器 lv.setAdapter(adapter); break;case SUCCESS_jsony:String jsonData = (String) msg.obj; //调用方法解析混合JSON数据ArrayList<Bean> al = readJsonyData(jsonData);//定义方法MyAdapter adapter = new MyAdapter(context,al);//显示在ListView上面.设置适配器lv.setAdapter(adapter);//tv.setText(jsonData);break;
case ERROR: Toast.makeText(MainActivity.this, "数据失败", 0).show();break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);//绑定控件tv = (TextView) findViewById(R.id.tv);
lv = (ListView) findViewById(R.id.lv);}/*** * 解析JSON_Object数据 ctrl + K * @param jsonData * @return */protected UserBean readJsonObject(String jsonData) {UserBean bean = null;//内置的JSON解析方法 JSONObject//直接创建对象try {JSONObject jsonObject = new JSONObject(jsonData);//用键取值String xname = jsonObject.getString("name");int xage = jsonObject.getInt("age");String xsex = jsonObject.getString("sex");//保存数据到beanbean = new UserBean(xname, xage, xsex);} catch (JSONException e) {e.printStackTrace();}return bean;}
/**** * 解析JSON_Array数据的操作 * @param jsonData * @return */protected ArrayList<UserBean> readJsonData(String jsonData) {ArrayList<UserBean> al = new ArrayList<UserBean>();try {//创建JSONAray的对象JSONArray jsonArray = new JSONArray(jsonData);//数组.遍历for循环 --- 条件://01.数组的长度是多少 jsonArray.length()//02.数组里面每一个元素的表示方式 jsonArray.getXXX(i);//循环遍历数组for (int i = 0; i < jsonArray.length(); i++) {//得到每一个元素JSONObject job = jsonArray.getJSONObject(i);//通过键KEY,取得值ValueString xname = job.getString("name");String xsex = job.getString("sex");int xage = job.getInt("age");//保存数据到JavaBean当中UserBean bean = new UserBean(xname, xage, xsex);//添加数据到集合当中al.add(bean);}} catch (Exception e) {e.printStackTrace();}return al;} /****
* 解析混合JSON数据的操作
* @param jsonData
* @return
*/
protected ArrayList<Bean> readJsonyData(String jsonData) {
ArrayList<Bean> al = new ArrayList<Bean>();
try {
//创建JSONObject的对象
JSONObject jsonObject01 = new JSONObject(jsonData);
//得到下一个数据
JSONObject jsonObject02 = jsonObject01.getJSONObject("result");
//得到下一个数据
JSONArray jsonArray01 = jsonObject02.getJSONArray("future");
//数组---循环遍历
//01.长度 jsonArray01.length()
//02.元素表示方式 jsonArray01.getXXX(i);
for (int i = 0; i < jsonArray01.length(); i++) {
//取得每一个元素
JSONObject jsonObject03 = jsonArray01.getJSONObject(i);
//得到数据
String xdata = jsonObject03.getString("date");
String xtemperature = jsonObject03.getString("temperature");
String xweather = jsonObject03.getString("weather");
String xweek = jsonObject03.getString("week");
String xwind = jsonObject03.getString("wind");
//创建对象
Bean b = new Bean(xdata, xtemperature, xweather, xweek, xwind);
//直接保存
al.add(b);
}
} catch (Exception e) {
e.printStackTrace();
}
return al;
}
//按钮的点击事件,点击的时候访问网络public void click(View v){//String url -->string data [JSON]//访问网络:开启子线程new Thread(){public void run() {//调用方法try {//得到JSON数据String data = WebHelper.loadData(url_object);//String data = WebHelper.loadData(url_array); //String data = WebHelper.loadData(url_jsony);
//得到消息的对象
Message msg = Message.obtain();
//设置what
msg.what = SUCCESS_object;
//msg.what = SUCCESS_array; //msg.what = SUCCESS_jsony;
//设置数据
msg.obj = data;
//发送消息
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
//得到消息的对象
Message msg = Message.obtain();
//设置what
msg.what = ERROR;
//发送消息
handler.sendMessage(msg);
}
};
}.start();
}
}
2-1.UserBean.java文件
package com.ittujunyong.simplejson;
public class UserBean {
private String name;
private int age;
private String sex;
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "UserBean [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
public UserBean(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
}
2-2.Bean.java文件
package com.ittujunyong.simplejson;
public class Bean {
private String date;
private String temperature;
private String weather;
private String week;
private String wind;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getWeek() {
return week;
}
public void setWeek(String week) {
this.week = week;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public Bean(String date, String temperature, String weather, String week,
String wind) {
super();
this.date = date;
this.temperature = temperature;
this.weather = weather;
this.week = week;
this.wind = wind;
}
@Override
public String toString() {
return "Bean [date=" + date + ", temperature=" + temperature
+ ", weather=" + weather + ", week=" + week + ", wind=" + wind
+ "]";
}
}
3.WebHelper.java文件
package com.ittujunyong.simplejson;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WebHelper {
public static String loadData(String path) throws Exception{
//定义返回值字符串
String result = null;
//---------------------------
//访问网络的操作:
//1.创建URL的对象 url
//2.通过url打开conn的对象
//3.通过conn得到code响应码
//4.判断响应码是否是200
//5.如果是200得到conn里面的inputStream的对象
//如果需要的是字符串,转换inputStream为字符串(文本)
//如果是图片数据,转换inputStream为位图 bitmap
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int code = conn.getResponseCode();
//判断
if (code == 200) {
//得到inputStream
InputStream is = conn.getInputStream();
//转换字符串
BufferedReader br = new BufferedReader(new InputStreamReader(is, "gbk"));
//定义临时变量
String line = null;
//创建StringBuffer的对象,追加数据
StringBuffer sb = new StringBuffer();
//循环读取数据
while((line = br.readLine())!=null){
//追加数据
sb.append(line);
}
//关闭IO流
br.close();
is.close();
//得到数据
result = sb.toString();
}
//----------------------------
//返回数据
return result;
}
}
4.MyAdapter.java文件
package com.ittujunyong.simplejson;
import java.util.ArrayList;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter{
private Context context;
private ArrayList<UserBean> al;
//构造方法,传递参数
public MyAdapter(Context context, ArrayList<UserBean> al) {
this.al = al;
this.context = context;
}
//得到条目总数
@Override
public int getCount() {
return al.size();
}
//无视
@Override
public Object getItem(int position) {
return null;
}
//无视
@Override
public long getItemId(int position) {
return 0;
}
//得到每一个条目的视图
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//定义视图
View vv = null;
//判断是不是第一次加载数据
if (convertView==null) {
//打气筒
vv = View.inflate(context, R.layout.item, null);
}else {
//复用视图
vv = convertView;
}
//关心控件
TextView nameTextView = (TextView) vv.findViewById(R.id.item_name);
TextView ageTextView = (TextView) vv.findViewById(R.id.item_age);
TextView sexTextView = (TextView) vv.findViewById(R.id.item_sex);
//得到数据
String name = al.get(position).getName();
String sex = al.get(position).getSex();
String age = al.get(position).getAge()+"";
//显示数据到视图上面
nameTextView.setText(name);
sexTextView.setText(sex);
ageTextView.setText(age);
/** TextView x1 = (TextView) vv.findViewById(R.id.item_1);
TextView x2 = (TextView) vv.findViewById(R.id.item_2);
TextView x3 = (TextView) vv.findViewById(R.id.item_3);
TextView x4 = (TextView) vv.findViewById(R.id.item_4);
TextView x5 = (TextView) vv.findViewById(R.id.item_5);
x1.setText(al.get(position).getDate());
x2.setText(al.get(position).getTemperature());
x3.setText(al.get(position).getWeather());
x4.setText(al.get(position).getWeek());
x5.setText(al.get(position).getWind()); *///返回数据return vv;}}
5.JsonUtil.java文件
package com.ittujunyong.play.util;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* 封装的是使用Gson解析json的方法
*
* @author Administrator
*
*/
public class JsonUtil {
/**
* 把一个map变成json字符串
*
* @param map
* @return
*/
public static String parseMapToJson(Map<?, ?> map) {
try {
Gson gson = new Gson();
return gson.toJson(map);
} catch (Exception e) {
}
return null;
}
/**
* 把一个json字符串变成对象
*
* @param json
* @param cls
* @return
*/
public static <T> T parseJsonToBean(String json, Class<T> cls) {
Gson gson = new Gson();
T t = null;
try {
t = gson.fromJson(json, cls);
} catch (Exception e) {
}
return t;
}
/**
* 把json字符串变成map
*
* @param json
* @return
*/
public static HashMap<String, Object> parseJsonToMap(String json) {
Gson gson = new Gson();
Type type = new TypeToken<HashMap<String, Object>>() {
}.getType();
HashMap<String, Object> map = null;
try {
map = gson.fromJson(json, type);
} catch (Exception e) {
}
return map;
}
/**
* 把json字符串变成集合 params: new TypeToken<List<yourbean>>(){}.getType(),
*
* @param json
* @param type
* new TypeToken<List<yourbean>>(){}.getType()
* @return
*/
public static List<?> parseJsonToList(String json, Type type) {
Gson gson = new Gson();
List<?> list = gson.fromJson(json, type);
return list;
}
/**
*
* 获取json串中某个字段的值,注意,只能获取同一层级的value
*
* @param json
* @param key
* @return
*/
public static String getFieldValue(String json, String key) {
if (TextUtils.isEmpty(json))
return null;
if (!json.contains(key))
return "";
JSONObject jsonObject = null;
String value = null;
try {
jsonObject = new JSONObject(json);
value = jsonObject.getString(key);
} catch (JSONException e) {
e.printStackTrace();
}
return value;
}
}
二、采用Gson框架解析
1.MainActivity.java文件
package com.ittujunyong.simplejson;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final int SUCCESS = 1;
protected static final int ERROR = 2;
private TextView tv; private ListView lv;
//使用到上下文的对象
private Context context = MainActivity.this;
// 定义路径private String url = "http://192.168.12.143:8080/json_object.txt";private String url = "http://192.168.12.143:8080/json_array.txt";
private String url = "http://192.168.12.143:8080/jsony.txt";// 定义Handlerprivate Handler handler = new Handler() {// 重写方法public void handleMessage(android.os.Message msg) {// 选择switch (msg.what) {case SUCCESS:String jsonData = (String) msg.obj;// 调用方法UserBean bean = readJsonObject(jsonData);// 显示数据tv.setText(bean.toString());break;
case SUCCESS:
String jsonData = (String) msg.obj;
//调用方法解析JSON数据
ArrayList<UserBean> al = readJsonData(jsonData);
//定义方法
MyAdapter adapter = new MyAdapter(context,al);
//显示在ListView上面.设置适配器
lv.setAdapter(adapter);
//tv.setText(jsonData);
break;
case SUCCESS:
String jsonData = (String) msg.obj;
// 调用方法解析混合JSON数据
ArrayList<Bean> al = readJsonyData(jsonData);
// 定义方法
MyAdapter adapter = new MyAdapter(context, al);
// 显示在ListView上面.设置适配器
lv.setAdapter(adapter);
// tv.setText(jsonData);
break;
case ERROR:
Toast.makeText(MainActivity.this, "数据失败", 0).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 关心控件
tv = (TextView) findViewById(R.id.tv); lv = (ListView) findViewById(R.id.lv);
}
/***
* 解析JSON_object数据 ctrl + K
*
* @param jsonData
* @return
*/
protected UserBean readJsonObject(String jsonData) {
UserBean bean = null;
//----------------------------------
//参数1:需要解析的JSON字符串
//参数2:解析生成类的字节码 ---> UserBean.class
bean = JsonUtil.parseJsonToBean(jsonData, UserBean.class);
//----------------------------------
return bean;
}
/****
* 解析JSON_array数据的操作
* @param jsonData
* @return
*/
protected ArrayList<UserBean> readJsonData(String jsonData) {
ArrayList<UserBean> al = new ArrayList<UserBean>();
//参数1:需要解析的JSON数据
//参数2:List集合的字节码.class new TypeToken<List<yourbean>>(){}.getType()
al = (ArrayList<UserBean>) JsonUtil.parseJsonToList(jsonData,new TypeToken<List<UserBean>>(){}.getType());
return al;
} /****
* 解析混合JSON数据的操作
*
* @param jsonData
* @return
*/
protected ArrayList<Bean> readJsonyData(String jsonData) {
ArrayList<Bean> al = new ArrayList<Bean>();
// 参数1:需要解析的JSON数据
// 参数2:解析的节点 result
String data01 = JsonUtil.getFieldValue(jsonData, "result");
// 参数1:需要解析的JSON数据
// 参数2:解析的节点 result
String data02 = JsonUtil.getFieldValue(data01, "future");
try {
//直接采用JSONArray去解析
JSONArray jsonArray = new JSONArray(data02);
//循环
for (int i = 0; i < jsonArray.length(); i++) {
//得到数据
JSONObject job = jsonArray.getJSONObject(i);
String xdate = job.getString("date");
String xtemperature = job.getString("temperature");
String xweather = job.getString("weather");
String xweek = job.getString("week");
String xwind = job.getString("wind");
//创建对象
Bean b = new Bean(xdate, xtemperature, xweather, xweek, xwind);
al.add(b);
}
} catch (Exception e) {
e.printStackTrace();
}
return al;
}
// 按钮的点击事件,点击的时候访问网络public void click(View v) {// String url -->string data [JSON]// 访问网络:开启子线程new Thread() {public void run() {// 调用方法try {// 得到JSON数据String data = WebHelper.loadData(url);// 得到消息的对象Message msg = Message.obtain();// 设置whatmsg.what = SUCCESS;// 设置数据msg.obj = data;// 发送消息handler.sendMessage(msg);} catch (Exception e) {e.printStackTrace();// 得到消息的对象Message msg = Message.obtain();// 设置whatmsg.what = ERROR;// 发送消息handler.sendMessage(msg);}};}.start();}}
4万+

被折叠的 条评论
为什么被折叠?



