日期:2014-05-16  浏览次数:20430 次

Android中Json应用实例介绍


?--效果图见下方附件:

?

?

?

1、首先看看什么是Json,简介如下:详情请点这里链接

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。

?

2、再来看看这次测试的Json源文件内容

{
???
??? "peoples": [
??????? {
??????????? "name": "张三",
??????????? "age": "22",
??????????? "tel": {
??????????? ??"hometel": "家庭电话1",
??????????? ??"companytel": "公司电话电话1"
??????????? ?}
??????? },
??????? {
??????????? "name": "李四",
??????????? "age": "36",
??????????? "tel": {
??????????? ??"hometel": "家庭电话2",
??????????? ??"companytel": "公司电话电话2"
??????????? ?}
??????? }
??? ]
}

?

3、了解了Json的相关介绍和语法之后,来看看怎么用程序将其内容解析出来,下面看解析该Json文件的代码

public static ArrayList<Person> getUsers(InputStream inputStream) throws Exception {

??ArrayList<Person> persons = new ArrayList<Person>();
??byte[] bts = StreamTool.readStream(inputStream);
??String contents = new String(bts, "gb2312");

??JSONArray personsArr = new JSONObject(contents).getJSONArray("peoples");

??System.out.println("Json文件内容 = " + contents);

??int personCount = personsArr.length();

??for (int i = 0; i < personCount; i++) {

???Person p = new Person();

???JSONObject person = (JSONObject) personsArr.opt(i);
???String name = person.getString("name");
???int age = person.getInt("age");

???// 得到电话的集合
???JSONObject tels = new JSONObject(person.getString("tel"));

???String homeTel = tels.getString("hometel");
???String cmpTel = tels.getString("companytel");

???p.setName(name);
???p.setAge(age);
???p.setHomeTel(homeTel);
???p.setCompanyTel(cmpTel);

???persons.add(p);
??}

??if (inputStream != null) {
???inputStream.close();
???System.out.println("流已关闭.....");
??}
??return persons;

?}

?

4、来写单元测试方法

public void testParser() {

??InputStream inputStream = getContext().getClassLoader()
????.getResourceAsStream("person.json");
??
??if (inputStream != null) {
???
???try {
????ArrayList<Person> persons = JsonParser.getUsers(inputStream);
????
????for (Person person : persons) {
?????System.out.println("person Info = " + person);
????}
???} catch (Exception e) {
????// TODO Auto-generated catch block
????e.printStackTrace();
???}
??}
?}

?

总结和建议:

1、android中除了可以用Json来完成数据交换,也可以用XML来完成数据交换,但是android官方推荐的是通过Json方式,因为用Js