Android Json解析
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。 它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 这些特性使JSON成为理想的数据交换语言。
JSON建构于两种结构:
- “名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
- 值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。
这些都是常见的数据结构。事实上大部分现代计算机语言都以某种形式支持它们。这使得一种数据格式在同样基于这些结构的编程语言之间交换成为可能。
详细情况参考:http://www.json.org/json-zh.html
在org.json包下有一些和Json相关的类,方便开发者进行和Json相关的一些操作。下面以一个简单的例子做说明,解析assets下的Json文件:
import java.io.ByteArrayOutputStream; import java.io.InputStream; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Handler.Callback; import android.widget.TextView; public class TestJsonActivity extends Activity { private TextView textView; private Handler mHandler = new Handler(new Callback() { @Override public boolean handleMessage(Message msg) { try { textView.append(msg.getData().getString("data")); return true; } catch (Exception e) { e.printStackTrace(); } return false; } }); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); textView = new TextView(this); setContentView(textView); parserJsonFileFromAsset(); } /** * 解析Assets文件夹下的JSON文件 */ private void parserJsonFileFromAsset() { new Thread(new Runnable() { @Override public void run() { InputStream inputStream = null; try { inputStream = getAssets().open("data.json"); JSONObject jsonObject = new JSONObject(inputStream2String(inputStream)); JSONArray dataListA = jsonObject.getJSONArray("data_list_a"); for (int i = 0, length = dataListA.length(); i < length; i++) { // 耗时5秒 Thread.sleep(5 * 1000); JSONObject dataObject = (JSONObject) dataListA.get(i); // 设置数据到DataInfo DataInfo dataInfo = new DataInfo(); dataInfo.setType("Data List A"); dataInfo.setId(dataObject.getString("id")); dataInfo.setName(dataObject.getString("name")); dataInfo.setAddress(dataObject.getString("address")); // 发送消息,更新UI Message msg = new Message(); Bundle data = new Bundle(); data.putString("data", dataInfo.toString()); msg.setData(data); mHandler.sendMessage(msg); } JSONArray dataListB = jsonObject.getJSONArray("data_list_b"); for (int i = 0, length = dataListB.length(); i < length; i++) { Thread.sleep(5 * 1000); JSONObject dataObject = (JSONObject) dataListB.get(i); DataInfo dataInfo = new DataInfo(); dataInfo.setType("Data List B"); dataInfo.setId(dataObject.getString("id")); dataInfo.setName(dataObject.getString("name")); dataInfo.setAddress(dataObject.getString("address")); Message msg = new Message(); Bundle data = new Bundle(); data.putString("data", dataInfo.toString()); msg.setData(data); mHandler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } } }).start(); } /** * * @param inputStream * @param bufferSize * @return * @throws Exception */ private String inputStream2String(InputStream inputStream, int bufferSize) throws Exception { int i = -1; byte[] b = new byte[bufferSize]; StringBuffer sb = new StringBuffer(); while ((i = inputStream.read(b)) != -1) { sb.append(new String(b, 0, i)); } return sb.toString(); } /** * * @param inputStream * @return * @throws Exception */ private String inputStream2String(InputStream inputStream) throws Exception { int i = -1; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((i = inputStream.read()) != -1) { baos.write(i); } return baos.toString(); } /** * * @author oss * */ class DataInfo { private String type; private String id; private String name; private String address; public DataInfo() { } public void setType(String type) { this.type = type; } public String getType() { return type; } public void setId(String id) { this.id = id; } public String getId() { return id; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAddress(String address) { this.address = address; } public String getAddress() { return address; } @Override public String toString() { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("Type: " + type); stringBuffer.append("\nID: " + id); stringBuffer.append("\nName: " + name); stringBuffer.append("\nAddress: " + address + "\n\n"); return stringBuffer.toString(); } } }
说明:
- mHandler:更新UI,从msg中获得需要的数据,并在UI中显示;
- 解析是一个比较费时的操作,所以放到线程中做,避免ANR的发生;
- Json解析相对容易理解,都是一些对象的获得,然后使用getter获的对应key的value即可;
- Thread.sleep(5 * 1000);模拟耗时操作;
被解析的数据格式:
{ "data_list_a":[ { "id":"11", "name":"name a 1", "address":"address a 1" } ], "data_list_b":[ { "id":"11", "name":"name b 1", "address":"address b 1" }, { "id":"22", "name":"name b 2", "address":"address b 2" } ] }
多说一句:解析代码比较少,大部分是JavaBean和使用Handler更新UI的代码!:)
相关推荐
nalanrumeng 2020-01-13
qianqianxiao 2019-11-04
Mexican 2011-10-12
翟浩浩Android 2013-01-13
leavesC 2019-06-29
88357660 2015-06-13
88377560 2014-03-31
kane 2014-03-31
88357660 2019-06-25
toperfect 2011-07-21
chinewwen 2016-08-17
SXIAOYI 2016-06-28
yinge00 2016-04-09
tcxingdechen 2015-11-27
Anything 2015-09-07
Urchindong 2015-03-26
家猫OR野猫 2014-12-11
pengjin 2014-12-10