安卓学习-XML,JSON解析;SAX,DOM,PULL机制–SAX和PULL类似

一.XML解析

安卓学习-XML,JSON解析;SAX,DOM,PULL机制–SAX和PULL类似_第1张图片

安卓学习-XML,JSON解析;SAX,DOM,PULL机制–SAX和PULL类似_第2张图片

 

案例:安卓学习-XML,JSON解析;SAX,DOM,PULL机制–SAX和PULL类似_第3张图片 点击按钮控制台打印

image

person.xml

<shanghaibaolei>
<person personid="1">
<name>xfei</name>
<age>20</age>
<sex>男</sex>
<tel>13760359165</tel>
</person>
<person personid="2">
<name>xxx</name>
<age>18</age>
<sex>女</sex>
<tel>12345678901</tel>
</person>
</shanghaibaolei>

Person.java

package com.example.administrator.xmlandjson;

/**
* Created by Administrator on 2016/4/2.
*/
public class Person {
int personid;
String name;
int age;
String sex;
String tel;

@Override
public String toString() {
return "Person{" +
"age=" + age +
", personid=" + personid +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", tel='" + tel + '\'' +
'}';
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.xmlandjson.MainActivity">


<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="XML PULL解析"
android:id="@+id/button"
android:onClick="pullParserClick"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>

ManActivity.java

package com.example.administrator.xmlandjson;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

//使用Pull解析XML文件
public void pullParserClick(View view) {
ArrayList<Person> list= parser();
for (int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
}

private ArrayList<Person> parser() {

ArrayList<Person> list = new ArrayList<Person>();
Person p = null;
//创建PULL解析器
XmlPullParser pull = Xml.newPullParser();
//StringReader sr=new StringReader(xml);
InputStream in = getResources().openRawResource(R.raw.person);
try {
//设置要解析的文件流
pull.setInput(in, "UTF-8");
//获取当前的事件类型
int eventType = pull.getEventType();



while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
String tag=pull.getName();
if("person".equals(tag))
{
p=new Person();
p.personid=Integer.parseInt(pull.getAttributeValue(null,"personid"));
}
else if("name".equals(tag))
{
p.name=pull.nextText();
}
else if("age".equals(tag))
{
p.age=Integer.parseInt(pull.nextText());
}
else if("sex".equals(tag))
{
p.sex=pull.nextText();
}
else if("tel".equals(tag))
{
p.tel=pull.nextText();
}
break;
case XmlPullParser.END_TAG:
if("person".equals(pull.getName()))
{
list.add(p);
}
break;
}
//获取下一个事件类型
eventType = pull.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
}

 

二.JSON解析

安卓学习-XML,JSON解析;SAX,DOM,PULL机制–SAX和PULL类似_第4张图片

安卓学习-XML,JSON解析;SAX,DOM,PULL机制–SAX和PULL类似_第5张图片

安卓学习-XML,JSON解析;SAX,DOM,PULL机制–SAX和PULL类似_第6张图片

安卓学习-XML,JSON解析;SAX,DOM,PULL机制–SAX和PULL类似_第7张图片

点击第一个按钮:

点击第二个按钮:

 

点击第三个按钮image

点击第四个按钮:image

引用GSON包安卓学习-XML,JSON解析;SAX,DOM,PULL机制–SAX和PULL类似_第8张图片google-gson-1.7.1-release.zip

Person.java

package com.example.administrator.json;

/**
* Created by Administrator on 2016/4/2.
*/
public class Person {
String firstName;
String lastName;
String email;

@Override
public String toString() {
return "Person{" +
"email='" + email + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}

raw目录下{

person.json

{
"user": [
{
"firstName": "xfei",
"lastName": "xiaofei",
"email": "[email protected]"
},
{
"firstName": "HLY",
"lastName": "huiliyi",
"email": "[email protected]"
}
]
}

person1.json

[
{
"firstName": "xfei",
"lastName": "xiaofei",
"email": "[email protected]"
},
{
"firstName": "HLY",
"lastName": "huiliyi",
"email": "[email protected]"
}
]

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.json.MainActivity">


<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="JsonReader解析JSON"
android:onClick="jsonReaderClick"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="生成JSON数据"
android:onClick="createJSONClick"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GSON解析JSON"
android:onClick="gsonParseJsonClick"
android:id="@+id/button3"
android:layout_below="@+id/button2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/button2"
android:layout_alignEnd="@+id/button2" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GSON生成JSON"
android:onClick="gsonToJsonClick"
android:id="@+id/button4"
android:layout_below="@+id/button3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/button3"
android:layout_alignEnd="@+id/button3" />
</RelativeLayout>

MainActivity.java

package com.example.administrator.json;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.JsonReader;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

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

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void jsonReaderClick(View view) {
ArrayList<Person> list = jsonReader();
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}

/*JsonReader解析JSON*/
private ArrayList<Person> jsonReader() {
/* String json="{" +
" \"phone\" : [\"12345678\", \"87654321\"]," +
" \"name\" : \"yuanzhifei89\"," +
" \"age\" : 100," +
" \"address\" : { \"country\" : \"china\", \"province\" : \"guangdong\" }," +
" \"married\" : false," +
"}";*/
ArrayList<Person> list = new ArrayList<Person>();
// JsonReader jr=new JsonReader(new StringReader(json));
Reader r = new InputStreamReader(getResources().openRawResource(R.raw.person));
JsonReader jr = new JsonReader(r);

try {
jr.beginObject();//开始解析对象
if (jr.hasNext()) {
if ("user".equals(jr.nextName())) {
jr.beginArray();//开始解析数组
while (jr.hasNext()) {
Person p = new Person();
jr.beginObject();//开始解析对象
while (jr.hasNext()) {
String name = jr.nextName();
if ("firstName".equals(name)) {
p.firstName = jr.nextString();
} else if ("lastName".equals(name)) {
p.lastName = jr.nextString();
} else if ("email".equals(name)) {
p.email = jr.nextString();
}
}
jr.endObject();//结束对象的解析
list.add(p);
}
jr.endArray();
}
}
jr.endObject();

} catch (IOException e) {
e.printStackTrace();
}
return list;
}

//生成JSON数据
public void createJSONClick(View view) {
ArrayList<Person> list = new ArrayList<Person>();
Person p1 = new Person();
p1.firstName = "路明非";
p1.lastName = "路鸣泽";
p1.email = "[email protected]";
Person p2 = new Person();
p2.firstName = "绘梨衣";
p2.lastName = "诺诺";
p2.email = "[email protected]";
list.add(p1);
list.add(p2);


JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
try {
for (int i = 0; i < list.size(); i++) {
Person p = list.get(i);
JSONObject obj = new JSONObject();
obj.put("firstName", p.firstName);
obj.put("lastName", p.lastName);
obj.put("email", p.email);
array.put(obj);
}
json.put("person", array);
} catch (JSONException e) {
e.printStackTrace();
}

//测试
System.out.println(json.toString());
}

//使用GSON解析JSON
public void gsonParseJsonClick(View view) {
Gson gson = new Gson();
Reader r = new InputStreamReader(getResources().openRawResource(R.raw.person1));
Type type = new TypeToken<ArrayList<Person>>() {
}.getType();
ArrayList<Person> list = gson.fromJson(r, type);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}

// class MyTypeToken extends TypeToken<ArrayList<Person>>{}
//GSON生成JSON
public void gsonToJsonClick(View view) {
ArrayList<Person> list = new ArrayList<Person>();
Person p1 = new Person();
p1.firstName = "路明非";
p1.lastName = "路鸣泽";
p1.email = "[email protected]";
Person p2 = new Person();
p2.firstName = "绘梨衣";
p2.lastName = "诺诺";
p2.email = "[email protected]";
list.add(p1);
list.add(p2);
Type type = new TypeToken<ArrayList<Person>>() {
}.getType();
Gson gson = new Gson();
String json = gson.toJson(list, type);
System.out.println(json);

}
}

你可能感兴趣的:(安卓学习-XML,JSON解析;SAX,DOM,PULL机制–SAX和PULL类似)