Android App中读取XML与JSON格式数据的基本方法示例

时间:2021-12-06 23:40:24

xml
假如有这样一个xml格式的数据:

?
1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<resources>
<customer name="luopeng" age="21" gender="1"   emial="dylankeepmoving@163.com"/>
<customer name="dylan" age="22" gender="2" emial="710097663@qq.com"/>
<customer name="android" age="6" gender="2" emial="android@gmail.com"/>
</resources>

下面我们来编写一个类来读取,此类的作用是点击按钮后在editview上显示资源文件(一个xml)中的内容,此例中会使用到xmlresourceparser

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class testxmlresourceparseractivity extends activity {
private edittext et;
private button mybutton;
 
@override
public void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.main);
 
  // 变量在内部类中使用的前提是此变量必须是final修饰的
  mybutton = (button) this.findviewbyid(r.id.btn01);
  et = (edittext) this.findviewbyid(r.id.edittext01);
  mybutton.setonclicklistener(new onclicklistener() {
    stringbuilder sb = new stringbuilder("");
    resources res = getresources();
    xmlresourceparser xrp = res.getxml(r.xml.test);
 
    @override
    public void onclick(view v) {
      int counter = 0;
      try {
        // 判断是否到了文件的结尾
        while (xrp.geteventtype() != xmlresourceparser.end_document) {
          //文件的内容的起始标签开始,注意这里的起始标签是test.xml文件里面<resources>标签下面的第一个标签
          if (xrp.geteventtype() == xmlresourceparser.start_tag) {
            string tagname = xrp.getname();
            if (tagname.endswith("customer")) {
              counter++;
              sb.append("这是第" + counter + "客户"+"\n");
              sb.append("姓名:"+xrp.getattributevalue(0)+"\n");
              sb.append("年龄:"+xrp.getattributevalue(1)+"\n");
              sb.append("性别:"+xrp.getattributevalue(2)+"\n");
              sb.append("邮箱:"+xrp.getattributevalue(3)+"\n\n");
            }
          }
          xrp.next();
        }
        et.settext(sb.tostring());
      } catch (xmlpullparserexception e) {
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
  });
}

json
创建json数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
try {
    //首先创建对象中的一个单个键值对
    jsonobject root = new jsonobject();
    root.put("cat", "it");
    //另一个键值对的值是一个数组,数组里装了3个json对象,所以再分别搞3个jsonobject对象存放键值对
    jsonobject lan1 = new jsonobject();
    lan1.put("id", "1");
    lan1.put("ide", "eclipse");
    lan1.put("name","java");
    jsonobject lan2 = new jsonobject();
    lan2.put("id", "2");
    lan2.put("ide", "xcode");
    lan2.put("name","swift");
    jsonobject lan3 = new jsonobject();
    lan3.put("id", "2");
    lan3.put("ide", "visual studio");
    lan3.put("name","c#");
    //在将这3个对象存入一个数组
    jsonarray array = new jsonarray();
    array.put(lan1);
    array.put(lan2);
    array.put(lan3);
    //再将数组作为键"languages"的值,构成一个对象
    root.put("languages", array);
    //本例中只将内容输出出来
    system.out.println(root.tostring());
 
  } catch (jsonexception e) {
    e.printstacktrace();
  }

读取json数据
assets/test.json

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
{
  "languages":[
    {"id":1,"ide":"eclipse","name":"java"},
    {"id":2,"ide":"xcode","name":"swift"},
    {"id":3,"ide":"visual studio","name":"c#"},
  ],
  "cat","it"
}
try {
    inputstream is = getresources().getassets().open("test.json");
    inputstreamreader isr = new inputstreamreader(is, "utf-8");
    bufferedreader br = new bufferedreader(isr);
    //将文本中的数据,都读取到一个stringbuilder当中
    string line;
    stringbuilder builder = new stringbuilder();
    while((line=br.readline()) != null ){
      builder.append(line);
    }
    br.close();
    isr.close();
 
    jsonobject root = new jsonobject(builder.tostring());
    //根据键,获得键对应的值,由于值是string类型,所以用getstring
    system.out.println("cat="+root.getstring("cat"));
    //根据键,获得键对应的数组,由于值是一个数组,所以用getjsonarray
    jsonarray array = root.getjsonarray("languages");
    //由于要遍历数组,所以创建一个for循环
    for(int i=0; i < array. length(); i++){
      //由于每一个数组当中的元素,也是一个新的json对象
      jsonobject lan = array.getjsonobject(i);
      system.out.println("-------------------");
      system.out.println("id="+lan.getint("id"));
      system.out.println("ide="+lan.getstring("name"));
      system.out.println("name="+lan.getstring("name"));
      log.i("tag","-------");
    }
 
  } catch (ioexception e) {
    e.printstacktrace();
  } catch (jsonexception e) {
    // todo auto-generated catch block
    e.printstacktrace();
  }