一、解析方法:
Android解析json有很多种方法,下面介绍三种方法:Android自带的org.json解析、Gson解析和Jackson解析。
优缺点对比:
Android自带的方法有点像xml的dom解析,遍历之后根据需要的key值去取数据,操作比较复杂,而且速度比较慢;Gson方法只需要建立一个对应json的javaBean类,就可以通过简单的操作解析出数据,而且速度比较快,还可以按需去取数据;Jackson方法是三种方法里面最快的一种,在数据量的的情况优势尤为明显,也是像Gson一样要建立对应的javaBean,但是缺点是一定要读取所有key,如果要按需解析的话可以拆分json来读取,操作比较麻烦。
PS:从服务器或从本地读取的json数据有可能含有BOM头,读入的话会导致json数据解析失败,所以需要去除BOM头,因为java在读取Unicode文件的时候,会统一把BOM变成“\uFEFF”,所以可以:
if(line.startsWith("\uFEFF")){
line = line.replace("\uFEFF", "");//去除BOM头
}
下面请看我学习json解析中运用到3个方法的例子(以下例子使用Android Studio编译)
二、Android Studio自带org.json解析:
1.解析一个json数据:
{
"student":[
{"id":1,"name":"小明","sex":"男","age":18,"height":175},
{"id":2,"name":"小红","sex":"女","age":19,"height":165},
{"id":3,"name":"小强","sex":"男","age":20,"height":185}
],
"cat":"it"
}
2.读入本地assets文件夹里面的student.json并解析
package scut.learngson;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EntityStudent student = new EntityStudent();
try {
InputStreamReader isr = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("assets/" + "student.json"));
//从assets获取json文件,和eclipse里面的方法不同,我搞了好久才发现
BufferedReader bfr = new BufferedReader(isr);//字节流转字符流
String line ;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bfr.readLine())!=null){
stringBuilder.append(line);
}//将JSON数据转化为字符串
JSONObject root = new JSONObject(stringBuilder.toString());
System.out.println("root:"+root.getString("cat"));//根据键名获取键值信息
JSONArray array = root.getJSONArray("student");
for (int i = 0;i < array.length();i++)
{
JSONObject stud = array.getJSONObject(i);
System.out.println("------------------");
System.out.print("id="+stud.getInt("id")+ ","));
System.out.print("name="+stud.getString("name")+ ","));
System.out.print("sex="+stud.getString("sex")+ ","));
System.out.print("age="+stud.getInt("age")+ ","));
System.out.println("height="+stud.getInt("height")+ ","));
bfr.close();
isr.close();
is.close();//依次关闭流
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
输出
System.out: ------------------
System.out: id=1,name=小明,sex=男,age=18,height=175,
System.out: id=2,name=小红,sex=女,age=19,height=165,
System.out: id=3,name=小强,sex=男,age=20,height=185,
三、Gson解析
1.Gson简单解析
一个JavaBean(json用gson转化的时候要有一个实体类对应):
PS:用Gson解析的话,JavaBean里面的属性不一定要全部和json数据里面的所有key对应,可以按需取数据。
package scut.learngson;
public class EntityStudent {
private int id;
private String name;
private String sex;
private int age;
private int height;
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public void setSex(String sex){
this.sex = sex;
}
public void setAge(int age){
this.age = age;
}
public void setHeight(int height){
this.height = height;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
public String getSex(){
return sex;
}
public int getAge(){
return age;
}
public int getHeight(){
return height;
}
public void show(){
System.out.print("id=" + id + ",");
System.out.print("name=" + name+",");
System.out.print("sex=" + sex+",");
System.out.print("age=" + age+",");
System.out.println("height=" + height + ",");
}
}
输出
System.out: id=1,name=小明,sex=男,age=18,height=175,
System.out: id=2,name=小红,sex=女,age=19,height=165,
System.out: id=3,name=小强,sex=男,age=20,height=185,
用gson进行简单的转换
package scut.learngson;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gson gson = new Gson();
EntityStudent student = new EntityStudent();
String json = "{\"id\":1,\"name\":\"小明\",\"sex\":\"男\",\"age\":18,\"height\":175}";
student = gson.fromJson(json,EntityStudent.class);//json数据转为单个类实体
student.show();
String json1 = gson.toJson(student);//转化为json
System.out.println(json1);
}
}
带泛型的List装类实体数组数据
package scut.learngson;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.reflect.TypeToken;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gson gson = new Gson();
String json = "[{\"id\":1,\"name\":\"小明\",\"sex\":\"男\",\"age\":18,\"height\":175},{\"id\":2,\"name\":\"小红\",\"sex\":\"女\",\"age\":19,\"height\":165},{\"id\":3,\"name\":\"小强\",\"sex\":\"男\",\"age\":20,\"height\":185}]";
List<EntityStudent> List = gson.fromJson(json, new TypeToken<List<EntityStudent>>(){}.getType());
//将JSON解析为带泛型的list
for (int i= 0;i<List.size();i++) {
EntityStudent stu = List.get(i);
stu.show();
}//显示实体数据
String json2 = gson.toJson(List);//转换为json
System.out.println(json2);
}
}
结果:
2.用Gson解析复杂json数据
重点是要根据json数据里面的结构写出一个对应的javaBean,规则是:
1.json的大括号对应一个对象,对象里面有key和value(值)。在Bean里面的类属性要和key同名。
2.json的方括号对应一个数组,所以在Bean里面对应的也是数组,数据里面可以有值或者对象。
3.如果数组里面只有值没有key,就说明它只是一个纯数组,如果里面有值有key,则说明是对象数组。纯数组对应Bean里面的数组,对象数组要在Bean里面建立一个内部类,类属性就是对应的对象里面的key,建立了之后要创建一个这个内部类的对象,名字对应数组名。
4.对象里面嵌套对象时候,也要建立一个内部类,和对象数组一样,这个内部类对象的名字就是父对象的key
json数据(从有道API获取到的):
{"translation":["车"],
"basic":
{ "us-phonetic":"kɑr",
"phonetic":"kɑː",
"uk-phonetic":"kɑː",
"explains":["n. 汽车;车厢","n. (Car)人名;(土)贾尔;(法、西)卡尔;(塞)察尔"]},
"query":"car",
"errorCode":0,
"web":[{"value":["汽车","车子","小汽车"],"key":"Car"},
{"value":["概念车","概念车","概念汽车"],"key":"concept car"},
{"value":["碰碰车","碰撞用汽车","碰碰汽车"],"key":"bumper car"}]
}
根据json数据的结构和key值写的一个简略的javabean
PS:这里的javaBean不是一个正规的javaBean,因为类属性都是public声明的,这样用来测试的话还可以,但是在实际应用中不安全,正规的javaBean可以参考下面Jackson解析复杂json数据的javaBean.
package scut.httpgson;
import java.util.List;
public class fanyi {
public String[] translation;
public basic basic;
public static class basic{
public String phonetic;
public String[] explains;
}
public String query;
public int errorCode;
public List<wb> web;
public static class wb{
public String[] value;
public String key;
}
public void show(){
for (int i = 0;i<translation.length;i++)
{
System.out.println(translation[i]);
}
System.out.println(basic.phonetic);
for (int i = 0;i<basic.explains.length;i++){
System.out.println(basic.explains[i]);
}
System.out.println(query);
System.out.println(errorCode);
for (int i = 0;i<web.size();i++){
for(int j = 0; j<web.get(i).value.length;j++)
{
System.out.println(web.get(i).value[j]);
}
System.out.println(web.get(i).key);
}
}
}
fanyi.java:
package scut.httpgson;
import java.util.List;
public class fanyi {
public String[] translation; //["车"]数组
public basic basic; //basic对象里面嵌套着对象,创建一个basic内部类对象
public static class basic{ //建立内部类
public String phonetic;
public String[] explains;
}
public String query;
public int errorCode;
public List<wb> web; //web是一个对象数组,创建一个web内部类对象
public static class wb{
public String[] value;
public String key;
}
public void show(){
for (int i = 0;i<translation.length;i++)
{
System.out.println(translation[i]);}
System.out.println(basic.phonetic);
for (int i = 0;i<basic.explains.length;i++){
System.out.println(basic.explains[i]);
}
System.out.println(query);
System.out.println(errorCode);
for (int i = 0;i<web.size();i++){
for(int j = 0; j<web.get(i).value.length;j++)
{
System.out.println(web.get(i).value[j]);
}
System.out.println(web.get(i).key);
}
}
}
MainActivity:
package scut.httpgson;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
private TextView tv;
private String json;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
findViewById(R.id.btnstart).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is,"utf-8");
BufferedReader bfr = new BufferedReader(isr);
json = bfr.readLine();
System.out.println(json);
Gson gson = new Gson();
fanyi fan = gson.fromJson(json,fanyi.class);
fan.show();
bfr.close();
isr.close();
is.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute("http://fanyi.youdao.com/openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car");
}
});
}
输出结果:
System.out: {"translation":["车"],"basic":{"us-phonetic":"kɑr","phonetic":"kɑː","uk-phonetic":"kɑː","explains":["n. 汽车;车厢","n. (Car)人名;(土)贾尔;(法、西)卡尔;(塞)察尔"]},"query":"car","errorCode":0,"web":[{"value":["汽车","小汽车","轿车"],"key":"Car"},{"value":["概念车","概念车","概念汽车"],"key":"concept car"},{"value":["碰碰车","碰撞用汽车","碰碰汽车"],"key":"bumper car"}]}
System.out: 车
System.out: kɑː
System.out: n. 汽车;车厢
System.out: n. (Car)人名;(土)贾尔;(法、西)卡尔;(塞)察尔
System.out: car
System.out: 0
System.out: 汽车
System.out: 小汽车
System.out: 轿车
System.out: Car
System.out: 概念车
System.out: 概念车
System.out: 概念汽车
System.out: concept car
System.out: 碰碰车
System.out: 碰撞用汽车
System.out: 碰碰汽车
System.out: bumper car
把有道翻译的单词car换成new,输出:
System.out: {"translation":["新"],"basic":{"us-phonetic":"nu","phonetic":"njuː","uk-phonetic":"njuː","explains":["adj. 新的,新鲜的;更新的;初见的","adv. 新近","n. (New)人名;(英)纽"]},"query":"new","errorCode":0,"web":[{"value":["新的","新建","新品"],"key":"new"},{"value":["新世纪","新世纪音乐","新纪元运动"],"key":"NEW AGE"},{"value":["新罕布什尔","新罕布什尔州","新罕布什尔州"],"key":"New Hampshire"}]}
System.out: 新
System.out: njuː
System.out: adj. 新的,新鲜的;更新的;初见的
System.out: adv. 新近
System.out: n. (New)人名;(英)纽
System.out: new
System.out: 0
System.out: 新的
System.out: 新建
System.out: 新品
System.out: new
System.out: 新世纪
System.out: 新世纪音乐
System.out: 新纪元运动
System.out: NEW AGE
System.out: 新罕布什尔
System.out: 新罕布什尔州
System.out: 新罕布什尔州
System.out: New Hampshire
四、Jackson解析json
1.用Jackson简单json的解析:
一个javaBean
和Gson解析不同,Jackson解析对应的javaBean必须把json数据里面的所有key都弄出来对应好
package scut.learnjackson;
public class Student {
private int id;
private String name;
private String sex;
private int age;
private int height;
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setSex(String sex){
this.sex = sex;
}
public String getSex(){
return sex;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public void setHeight(int height){
this.height = height;
}
public int getHeight(){
return height;
}
public String toString(){
return id+" "+name+" "+sex+" "+age+" "+height;
}
}
解析简单的json对象:
package scut.learnjackson;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String json = "{\"id\":1,\"name\":\"小明\",\"sex\":\"男\",\"age\":18,\"height\":175}";
ObjectMapper objectMapper = new ObjectMapper();
try {
Student student = objectMapper.readValue(json,Student.class);
System.out.println(student.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出:
1 小明 男 18 175
2.解析简单的json对象数组:
package scut.learnjackson;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String json = "[{\"id\":1,\"name\":\"小明\",\"sex\":\"男\",\"age\":18,\"height\":175},{\"id\":2,\"name\":\"小红\",\"sex\":\"女\",\"age\":19,\"height\":165},{\"id\":3,\"name\":\"小强\",\"sex\":\"男\",\"age\":20,\"height\":185}]";
ObjectMapper objectMapper = new ObjectMapper();
try {
list = objectMapper.readValue(json,list.getClass());
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class,Student.class);
ArrayList<Student> list = objectMapper.readValue(json, javaType);//用ArrayList装json数组数据
System.out.println(list.toString());//ArrayList的toString方法
System.out.println(list.get(0).toString());//Student类的toString
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出:
[1 小明 男 18 175, 2 小红 女 19 165, 3 小强 男 20 185]
1 小明 男 18 175
3.用Jackson解析复杂的json数据
json数据:
{"student":
[
{"id":1,"name":"小明","sex":"男","age":18,"height":175,"date":[2013,8,11]},
{"id":2,"name":"小红","sex":"女","age":19,"height":165,"date":[2013,8,23]},
{"id":3,"name":"小强","sex":"男","age":20,"height":185,"date":[2013,9,1]}
],
"grade":"2"
}
建立对应的javaBean:
建立javaBean的对应规则和gson一样
package scut.learnjackson;
import java.util.ArrayList;
import java.util.List;
class test {
private List<stu> student = new ArrayList<stu>();
private int grade;
public void setStudent(List<stu> student){
this.student = student;
}
public List<stu> getStudent(){
return student;
}
public void setGrade(int grade){
this.grade = grade;
}
public int getGrade(){
return grade;
}
private static class stu {
private int id;
private String name;
private String sex;
private int age;
private int height;
private int[] date;
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setSex(String sex){
this.sex = sex;
}
public String getSex(){
return sex;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public void setHeight(int height){
this.height = height;
}
public int getHeight(){
return height;
}
public void setDate(int[] date){
this.date = date;
}
public int[] getDate(){
return date;
}
}
public String tostring(){
String str = "";
for (int i = 0;i<student.size();i++){
str += student.get(i).getId() + " " + student.get(i).getName() + " " + student.get(i).getSex() + " " + student.get(i).getAge() + " " + student.get(i).getHeight() ;
for (int j = 0;j<student.get(i).getDate().length;j++) {
str += student.get(i).getDate()[j]+ " " ;
}
str += "\n";
}
str += "\n"+getGrade();
return str;
}
}
Mainactivity
package scut.learnjackson;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ObjectMapper objectMapper = new ObjectMapper();
try {
InputStreamReader isr = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("assets/" + "student.json"),"utf-8");
//从assets获取json文件
BufferedReader bfr = new BufferedReader(isr);
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bfr.readLine())!=null){
stringBuilder.append(line);
}//将JSON数据转化为字符串
System.out.println(stringBuilder.toString());
System.out.println(tes.tostring());
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出:
System.out: {"student": [ {"id":1,"name":"小明","sex":"男","age":18,"height":175,"date":[2013,8,11]}, {"id":2,"name":"小红","sex":"女","age":19,"height":165,"date":[2013,8,23]}, {"id":3,"name":"小强","sex":"男","age":20,"height":185,"date":[2013,9,1]} ], "grade":"2"}
System.out: 1 小明 男 18 1752013 8 11
System.out: 2 小红 女 19 1652013 8 23
System.out: 3 小强 男 20 1852013 9 1
System.out: 2
以上就是本人所总结的解析json数据的三种方法,如果要解析少量数据json数据的话建议使用Gson解析,方便快捷,如果解析大量json数据的话建议用Jackson解析,性能高效。
希望我分享的经验能帮助大家,转载请注明原创地址:
炎之铠的博客:http://blog.csdn.net/totond/article/details/51077386