Json解析小结(Android)------综合(JsonObject+JsonArray)

综合型的json格式比较复杂

你需要分析每一层的节点

下面贴出被解析的json数据(本人只解析了部分节点)

{
    "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
}

根据不同的节点编写不同的业务Bean

下面是我所解析节点对的应业务Bean(其他的节点解析原理相同)

package com.liangfeng.jsonobject;

public class MyBean {
	private String temperature;
	private String weather;
	private String wind;
	private String week;
	private String 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 getWind() {
		return wind;
	}
	public void setWind(String wind) {
		this.wind = wind;
	}
	public String getWeek() {
		return week;
	}
	public void setWeek(String week) {
		this.week = week;
	}
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
	@Override
	public String toString() {
		return "MyBean [temperature=" + temperature + ", weather=" + weather
				+ ", wind=" + wind + ", week=" + week + ", date=" + date + "]";
	}
	
}

这里说一下解析的思路

由我的业务Bean可以看出

我解析的是result和它的子节点future

json的格式类似于键值对

所以我用节点名获取获取节点的内容(使用工具类)

接下来的操作其实就是解析JsonObject和JsonArray

package com.liangfeng.jsonobject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.reflect.TypeToken;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.renderscript.Type;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	protected static final int SUCCESS = 0;

	protected static final int ERROR = 1;

	// 获取控件
	private EditText et_path;
	private TextView tv_show;
	private List<MyBean> list;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			//
			String json = (String) msg.obj;
			switch (msg.what) {
			case SUCCESS:
				//解析第一层节点
				String json1 = JsonUtil.getFieldValue(json, "result");
				//解析第er层节点
				String json2 = JsonUtil.getFieldValue(json1, "future");
				//将json数组转为集合
				List<MyBean> list1 = (List<MyBean>) JsonUtil.parseJsonToList(json2,  new TypeToken<List<MyBean>>(){}.getType());
				//遍历集合
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < list1.size(); i++) {
					MyBean bean = list1.get(i);
					sb.append("temperature:").append(bean.getTemperature()).append("\n");
					sb.append("weather:").append(bean.getWeather()).append("\n");
					sb.append("wind:").append(bean.getWind()).append("\n");
					sb.append("week:").append(bean.getWeek()).append("\n");
					sb.append("date:").append(bean.getDate()).append("\n").append("-------------\n");
				}
				// 设置textView的内容
				tv_show.setText(sb.toString());
				break;
			case ERROR:
				Toast.makeText(MainActivity.this, "网络错误,请检查连接", 0).show();
				break;

			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 初始化
		et_path = (EditText) findViewById(R.id.et_path);
		tv_show = (TextView) findViewById(R.id.tv_show);
		list = new ArrayList<MyBean>();
	}

	// 点击事件
	public void click(View view) {
		// 获取网络路径
		final String path = et_path.getText().toString().trim();
		// 判断是否为空
		if (TextUtils.isEmpty(path)) {
			//
			Toast.makeText(this, "网络路径不能为空", 0).show();
			return;
		}
		// 在子线程中进行网络操作
		new Thread() {
			public void run() {
				// 获取URL对象,传入路径
				// 获取响应码
				try {
					callNetwork(path);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					//
					// 发送消息
					Message message = Message.obtain();
					message.what = ERROR;
					handler.sendMessage(message);
				}

			}

			private void callNetwork(final String path)
					throws MalformedURLException, IOException,
					ProtocolException, Exception {
				URL url = new URL(path);
				// 获取httpURL连接
				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				// 设置请求方式get
				connection.setRequestMethod("GET");
				int code = connection.getResponseCode();
				// 判断响应码
				if (code == 200) {
					// 获取返回的数据流
					InputStream stream = connection.getInputStream();
					// 将数据流转为字符串
					String data = JsonTool.to_String(stream);
					// 发送消息
					Message message = Message.obtain();
					message.what = SUCCESS;
					message.obj = data;
					handler.sendMessage(message);
				}
			};
		}.start();

	}
}

下面贴出源码中使用的工具类(需要导入一个gson包)

package com.liangfeng.jsonobject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class JsonTool {

	public static String to_String(InputStream stream) throws Exception {
		String data = null;
		//获取内存输出流对象
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		//设置读取长度
		byte [] len = new byte [1024];
		//设置接受变量
		int b = -1;
		//循环读取
		while (( b = stream.read(len)) != -1) {
			//读取长度		起始位置		字节数据
			baos.write(len, 0, b);
		}
		//关流
		baos.close();
		stream.close();
		data = baos.toString("gbk");
		//返回tostring
		return data;
	}
}
package com.liangfeng.jsonobject;

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;
	}

}

 

转载于:https://my.oschina.net/Liangfeng/blog/759777

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值