Android中解析JSON_通过GSON(1)




要创建和解析JSON数据,也可以使用GSON来完成。GSON是Google提供的用来在Java对象和JSON数据之间进行映射的Java类库。

使用GSON,可以很容易的将一串JSON数据转换为一个Java对象,或是将一个Java对象转换为相应的JSON数据。 

1.GSON的两个重要方法

  在GSON的API中,提供了两个重要的方法:toJson()和fromJson()方法。其中,toJson()方法用来实现将Java对象转换为相应的JSON数据,fromJson()方法则用来实现将JSON数据转换为相应的Java对象。

1.1 toJson()方法

  toJson()方法用于将Java对象转换为相应的JSON数据,主要有以下几种形式:

  (1)String toJson(JsonElement jsonElement);

  (2)String toJson(Object src);

  (3)String toJson(Object src, Type typeOfSrc);

  其中,方法(1)用于将JsonElement对象(可以是JsonObject、JsonArray等)转换成JSON数据;方法(2)用于将指定的Object对象序列化成相应的JSON数据;方法(3)用于将指定的Object对象(可以包括泛型类型)序列化成相应的JSON数据。

1.2 fromJson()方法

  fromJson()方法用于将JSON数据转换为相应的Java对象,主要有以下几种形式:

  (1)<T> T fromJson(JsonElement json, Class<T> classOfT);

  (2)<T> T fromJson(JsonElement json, Type typeOfT);

  (3)<T> T fromJson(JsonReader reader, Type typeOfT);

  (4)<T> T fromJson(Reader reader, Class<T> classOfT);

  (5)<T> T fromJson(Reader reader, Type typeOfT);

  (6)<T> T fromJson(String json, Class<T> classOfT);

  (7)<T> T fromJson(String json, Type typeOfT);

  以上的方法用于将不同形式的JSON数据解析成Java对象。


JSON数据的解析:

解析JSON数据, 首先需要明确待解析的是JSON Object还是JSON array, 然后需要确定采用哪种解析技术.

android平台上一般有2种解析技术可供选择:android内置的org.json包和google的开源gson库.

以下将分别采用这两种技术解析JSON对象和JSON数组来比较学习GSon的使用方法。


1.  采用android内置的org.json包解析JSON对象.

假设待解析的JSON数据为

json = "{\"name\":\"coolxing\", \"age\"=24, \"male\":true, \"address\":{\"street\":\"huiLongGuan\", \"city\":\"beijing\", \"country\":\"china\"}}",

其中\用于转义表达式中的双引号. 首先需要定义2个JavaBean和json对象的数据类型匹配:

  1. package text.com.bean;  
  2.   
  3. public class Address {  
  4.     private String street;  
  5.     private String city;  
  6.     private String country;  
  7.   
  8.     public Address() {  
  9.         super();  
  10.     }  
  11.   
  12.     public Address(String street, String city, String country) {  
  13.         super();  
  14.         this.street = street;  
  15.         this.city = city;  
  16.         this.country = country;  
  17.     }  
  18.   
  19.     public String getStreet() {  
  20.         return street;  
  21.     }  
  22.   
  23.     public void setStreet(String street) {  
  24.         this.street = street;  
  25.     }  
  26.   
  27.     public String getCity() {  
  28.         return city;  
  29.     }  
  30.   
  31.     public void setCity(String city) {  
  32.         this.city = city;  
  33.     }  
  34.   
  35.     public String getCountry() {  
  36.         return country;  
  37.     }  
  38.   
  39.     public void setCountry(String country) {  
  40.         this.country = country;  
  41.     }  
  42.   
  43.     @Override  
  44.     public String toString() {  
  45.         return "Address [street=" + street + ", city=" + city + ", country="  
  46.                 + country + "]";  
  47.     }  
  48.   
  49. }  
package text.com.bean;

public class Address {
	private String street;
	private String city;
	private String country;

	public Address() {
		super();
	}

	public Address(String street, String city, String country) {
		super();
		this.street = street;
		this.city = city;
		this.country = country;
	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	@Override
	public String toString() {
		return "Address [street=" + street + ", city=" + city + ", country="
				+ country + "]";
	}

}


  1. package text.com.bean;  
  2.   
  3. public class Person {  
  4.     private String name;  
  5.     private int age;  
  6.     private boolean male;  
  7.     private Address address;  
  8.   
  9.     public Person() {  
  10.         super();  
  11.     }  
  12.   
  13.     public Person(String name, int age, boolean male, Address address) {  
  14.         super();  
  15.         this.name = name;  
  16.         this.age = age;  
  17.         this.male = male;  
  18.         this.address = address;  
  19.     }  
  20.   
  21.     public String getName() {  
  22.         return name;  
  23.     }  
  24.   
  25.     public void setName(String name) {  
  26.         this.name = name;  
  27.     }  
  28.   
  29.     public int getAge() {  
  30.         return age;  
  31.     }  
  32.   
  33.     public void setAge(int age) {  
  34.         this.age = age;  
  35.     }  
  36.   
  37.     public boolean isMale() {  
  38.         return male;  
  39.     }  
  40.   
  41.     public void setMale(boolean male) {  
  42.         this.male = male;  
  43.     }  
  44.   
  45.     public Address getAddress() {  
  46.         return address;  
  47.     }  
  48.   
  49.     public void setAddress(Address address) {  
  50.         this.address = address;  
  51.     }  
  52.   
  53.     @Override  
  54.     public String toString() {  
  55.         return "Person [name=" + name + ", age=" + age + ", male=" + male  
  56.                 + ", address=" + address + "]";  
  57.     }  
  58.   
  59. }  


首先使用方法一(org.json包下的工具类)解析,代码如下:

  1. JSONObject jsonObject = new JSONObject(json);  
  2. String name = jsonObject.getString("name");  
  3. int age = jsonObject.getInt("age");  
  4. boolean male = jsonObject.getBoolean("male");  
  5. JSONObject addressJSON = jsonObject.getJSONObject("address");  
  6. String street = addressJSON.getString("street");  
  7. String city = addressJSON.getString("city");  
  8. String country = addressJSON.getString("country");  
  9. Address address = new Address(street, city, country);  
  10. Person person = new Person(name, age, male, address);  
  11. System.out.println(person);  
JSONObject jsonObject = new JSONObject(json);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean male = jsonObject.getBoolean("male");
JSONObject addressJSON = jsonObject.getJSONObject("address");
String street = addressJSON.getString("street");
String city = addressJSON.getString("city");
String country = addressJSON.getString("country");
Address address = new Address(street, city, country);
Person person = new Person(name, age, male, address);
System.out.println(person);

LogCat的输出为:

Person [name=coolxing, age=24, male=true, address=Address [street=huiLongGuan, city=beijing, country=china]], 

说明已经正确解析了JSON对象.


2. 采用GSON库解析JSON对象. 假设待解析的JSON数据是json = "{\"name\":\"coolxing\", \"age\"=24, \"male\":true, \"address\":{\"street\":\"huiLongGuan\", \"city\":\"beijing\", \"country\":\"china\"}}",

首先需要到http://code.google.com/p/google-gson/下载jar包, 并将其添加到项目中. 具体的解析代码如下:

  1. Gson gson = new Gson();  
  2. Person person = gson.fromJson(json, Person.class);  
  3. System.out.println(person);  
Gson gson = new Gson();
Person person = gson.fromJson(json, Person.class);
System.out.println(person);

LogCat的输出为:

Person [name=coolxing, age=24, male=true, address=Address [street=huiLongGuan, city=beijing, country=china]], 

说明已经正确解析了JSON对象, 是不是很简单?


3. 采用android内置的org.json包解析JSON数组. 假设待解析的JSON数据为

json = "[{\"name\":\"coolxing\", \"age\"=24, \"male\":true, \"address\":{\"street\":\"huiLongGuan\", \"city\":\"beijing\", \"country\":\"china\"}}, {\"name\":\"min\", \"age\"=20, \"male\":false, \"address\":{\"street\":\"heiShiJiao\", \"city\":\"daLian\", \"country\":\"china\"}}]",

解析代码如下:

  1. List<Person> persons = new ArrayList<Person>();  
  2. JSONArray jsonArray = new JSONArray(json);  
  3. for(int i = 0; i < jsonArray.length(); i++) {  
  4. JSONObject jsonObject = jsonArray.getJSONObject(i);  
  5. String name = jsonObject.getString("name");  
  6. int age = jsonObject.getInt("age");  
  7. boolean male = jsonObject.getBoolean("male");  
  8. JSONObject addressJSON = jsonObject.getJSONObject("address");  
  9. String street = addressJSON.getString("street");  
  10. String city = addressJSON.getString("city");  
  11. String country = addressJSON.getString("country");  
  12. Address address = new Address(street, city, country);  
  13. Person person = new Person(name, age, male, address);  
  14. persons.add(person);  
  15. }  
  16. System.out.println(persons);  


4. 采用gson库解析JSON数组. 待解析的JSON数据同上, 具体代码为:

  1. Gson gson = new Gson();  
  2. Type listType = new TypeToken<List<Person>>(){}.getType();  
  3. List<Person> persons = gson.fromJson(json, listType);  
Gson gson = new Gson();
Type listType = new TypeToken<List<Person>>(){}.getType();
List<Person> persons = gson.fromJson(json, listType);
LogCat的输出为
[Person [name=coolxing, age=24, male=true, address=Address [street=huiLongGuan, city=beijing, country=china]], Person [name=min, age=20, male=false, address=Address [street=heiShiJiao, city=daLian, country=china]]],
说明已经正确解析了JSON数组.
new TypeToken<List<Person>>(){}.getType(); 这句代码表示创建一个 TypeToken的匿名子类对象, 并调用该对象的getType()方法.
org.json包和gson库还有很多其他有用的API, 需要的时候可查看文档. 比如有的时候需要通过java对象或java集合和数组生成json数据上传给服务器, 当然你可以自我构造json字符串, 但会很麻烦. 这个时候就可以使用其中的有关API, 方便的完成这项工作。

测试用例:

  1. package text.com;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.lang.reflect.Type;  
  8. import java.util.List;  
  9.   
  10. import text.com.bean.Address;  
  11. import text.com.bean.Person;  
  12.   
  13. import com.google.gson.Gson;  
  14. import com.google.gson.reflect.TypeToken;  
  15.   
  16. public class JsonTest {  
  17.     String jsonString = "";  
  18.   
  19.     public static void main(String[] args) {  
  20.         // Person p1 = new Person("zhangsan", 12, true, new Address("北京", "海淀区",  
  21.         // "30号"));  
  22.         // Person p2 = new Person("zhangsan", 12, true, new Address("北京", "海淀区",  
  23.         // "30号"));  
  24.         // Person p3 = new Person("zhangsan", 12, true, new Address("北京", "海淀区",  
  25.         // "30号"));  
  26.         // List<Person> list = new ArrayList<Person>();  
  27.         // list.add(p1);  
  28.         // list.add(p2);  
  29.         // list.add(p3);  
  30.         // Gson gson = new Gson();  
  31.         // Type typeOfT = new TypeToken<List<Person>>(){}.getType();  
  32.         // String json = gson.toJson(list, typeOfT);  
  33.         // System.out.println("json:"+json);  
  34.   
  35.         // String str = readTxtFile("D:\\cjjworkspace\\Test\\json.txt");  
  36.         // System.out.println("文件内容:" + str);  
  37.          Gson gson = new Gson();  
  38.         // Type typeOfT = new TypeToken<List<Person>>(){}.getType();  
  39.         // List<Person> personList = gson.fromJson(str, typeOfT);  
  40.   
  41.         Person p1 = new Person("zhangsan"12truenew Address("北京""海淀区""30号"));  
  42.         Type typeOfT = new TypeToken<Person>(){}.getType();  
  43.         String str = gson.toJson(p1, typeOfT);  
  44.         System.out.println(str);  
  45.     }  
  46.   
  47.     public static String readTxtFile(String filePath) {  
  48.         String encoding = "utf-8";  
  49.         StringBuilder sb = new StringBuilder();  
  50.         try {  
  51.             File file = new File(filePath);  
  52.             if (file.isFile() && file.exists()) { // 判断文件是否存在  
  53.                 InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式  
  54.                 BufferedReader bufferedReader = new BufferedReader(read);  
  55.                 String str = "";  
  56.                 while ((str = bufferedReader.readLine()) != null) {  
  57.                     sb.append(str);  
  58.                 }  
  59.                 read.close();  
  60.                 return sb.toString();  
  61.             } else {  
  62.                 System.out.println("找不到指定的文件");  
  63.                 return null;  
  64.             }  
  65.         } catch (Exception e) {  
  66.             System.out.println("读取文件内容出错");  
  67.             e.printStackTrace();  
  68.         }  
  69.         return sb.toString();  
  70.     }  
  71. }  

通过以上比较,我们可发发现通过GSON解析json数据,相对于org.json方便的多。

以上简单说明是将json数据解析后转化为Java对象,同时,我们也可以通过Gson将Java对象方便的转化为json对象。

例如:

package cn.sunzn.gson;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import cn.sunzn.bean.Person;

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

public class GsonActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Gson gson = new Gson();

        /**
         * 将给定的 JSON 字符串转换成指定的类型对象
         */
        String json = "{\"name\":\"Tom\",\"age\":90}";
        Person person = gson.fromJson(json, Person.class);
        Log.e("GSON", person.toString());

        /**
         * 将给定的目标对象转换成 JSON 格式的字符串
         */
        String json_Person = gson.toJson(person);
        Log.e("GSON", json_Person);

        /**
         * 将给定的集合对象转换成 JSON 格式的字符串
         */
        ArrayList<Person> persons = new ArrayList<Person>();
        Collections.addAll(persons, new Person("tom", 10), new Person("jon", 20));
        String json_list = gson.toJson(persons);
        Log.e("GSON", json_list);

        /**
         * 将给定的 JSON 格式字符串转换为带泛型的集合对象
         */
        List<Person> retList = gson.fromJson(json_list, new TypeToken<List<Person>>() {}.getType());
        for (Person p : retList) {
            Log.e("GSON", p.toString());
        }
    }
}

Gson 解析 Json 运行结果

02-19 07:39:23.467: E/GSON(669): Person [name=Tom, age=90]
02-19 07:39:23.487: E/GSON(669): {"name":"Tom","age":90}
02-19 07:39:23.517: E/GSON(669): [{"name":"tom","age":10},{"name":"jon","age":20}]
02-19 07:39:23.547: E/GSON(669): Person [name=tom, age=10]
02-19 07:39:23.547: E/GSON(669): Person [name=jon, age=20]

Gson 转换过程中使用的实体类 Person

package cn.sunzn.bean;

import com.google.gson.annotations.Expose;

public class Person {
    @Expose
    private String name;
    @Expose
    private int age;

    public Person() {
        super();
    }

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

}


通过GSON解析复杂的json对象实例:


数据格式:

  1. {  
  2.     "data": {  
  3.         "partnerteamlist": [  
  4.             {  
  5.                 "pteamId"72825,  
  6.                 "ptitle""随摄影/共6套服装/准爸准妈共拍/免费肚画/底片全送。",  
  7.                 "pteamprice"288  
  8.             },  
  9.             {  
  10.                 "pteamId"72598,  
  11.                 "ptitle""随摄影/拍摄200张/4本相册/品质拍摄/送全新婚纱。",  
  12.                 "pteamprice"2888  
  13.             },  
  14.             {  
  15.                 "pteamId"72613,  
  16.                 "ptitle""随摄影/送全新婚纱/多外景拍摄/服装不限数量/绝无二次消费!",  
  17.                 "pteamprice"3699  
  18.             },  
  19.             {  
  20.                 "pteamId"72638,  
  21.                 "ptitle""随摄影/服装不限数量/高品质拍摄260张/送全新婚纱。",  
  22.                 "pteamprice"4299  
  23.             },  
  24.             {  
  25.                 "pteamId"72716,  
  26.                 "ptitle""随摄影/3组服装造型/内外景拍摄/完全透明消费!",  
  27.                 "pteamprice"388  
  28.             }  
  29.         ],  
  30.         "liketeamlist": [  
  31.             {  
  32.                 "lteamId"65886,  
  33.                 "ltitle""爱丽尔婚纱摄影/2本相册/6套服装造型/拍摄不限最低拍摄150张。",  
  34.                 "limage""http://img.pztuan.com/upfile/team/2013/0712/201307120257551465.jpg",  
  35.                 "lteamprice"518,  
  36.                 "lmarketprice"3999  
  37.             },  
  38.             {  
  39.                 "lteamId"57133,  
  40.                 "ltitle""陶冶摄影/婚纱闺蜜/6组服装造型/拍摄不低于120张!",  
  41.                 "limage""http://img.pztuan.com/upfile/team/2013/0628/201306281115249737.jpg",  
  42.                 "lteamprice"580,  
  43.                 "lmarketprice"3380  
  44.             }  
  45.         ],  
  46.         "feedbacks": {  
  47.             "feedbacklist": [  
  48.                 {  
  49.                     "comment""5分",  
  50.                     "createtime""2014.07.08 13:38",  
  51.                     "score"5,  
  52.                     "username""l***2"  
  53.                 }  
  54.             ],  
  55.             "totalcount"1,  
  56.             "totalscore"5  
  57.         }  
  58.     },  
  59.     "err"null,  
  60.     "state"1  
  61. }  
{
    "data": {
        "partnerteamlist": [
            {
                "pteamId": 72825,
                "ptitle": "随摄影/共6套服装/准爸准妈共拍/免费肚画/底片全送。",
                "pteamprice": 288
            },
            {
                "pteamId": 72598,
                "ptitle": "随摄影/拍摄200张/4本相册/品质拍摄/送全新婚纱。",
                "pteamprice": 2888
            },
            {
                "pteamId": 72613,
                "ptitle": "随摄影/送全新婚纱/多外景拍摄/服装不限数量/绝无二次消费!",
                "pteamprice": 3699
            },
            {
                "pteamId": 72638,
                "ptitle": "随摄影/服装不限数量/高品质拍摄260张/送全新婚纱。",
                "pteamprice": 4299
            },
            {
                "pteamId": 72716,
                "ptitle": "随摄影/3组服装造型/内外景拍摄/完全透明消费!",
                "pteamprice": 388
            }
        ],
        "liketeamlist": [
            {
                "lteamId": 65886,
                "ltitle": "爱丽尔婚纱摄影/2本相册/6套服装造型/拍摄不限最低拍摄150张。",
                "limage": "http://img.pztuan.com/upfile/team/2013/0712/201307120257551465.jpg",
                "lteamprice": 518,
                "lmarketprice": 3999
            },
            {
                "lteamId": 57133,
                "ltitle": "陶冶摄影/婚纱闺蜜/6组服装造型/拍摄不低于120张!",
                "limage": "http://img.pztuan.com/upfile/team/2013/0628/201306281115249737.jpg",
                "lteamprice": 580,
                "lmarketprice": 3380
            }
        ],
        "feedbacks": {
            "feedbacklist": [
                {
                    "comment": "5分",
                    "createtime": "2014.07.08 13:38",
                    "score": 5,
                    "username": "l***2"
                }
            ],
            "totalcount": 1,
            "totalscore": 5
        }
    },
    "err": null,
    "state": 1
}


实体类(里面的成员变量和接口的返回值名称一 一对应才能保证解析正确):

package com.pztuan.entity;  
  1.   
  2. import java.util.List;  
  3.   
  4. public class OtherDetail {  
  5.   
  6.     private int state;  
  7.     private List<err> err;  
  8.     private OtherDetail2 data;  
  9.   
  10.     public int getState() {  
  11.         return state;  
  12.     }  
  13.   
  14.     public void setState(int state) {  
  15.         this.state = state;  
  16.     }  
  17.   
  18.     public List<err> getErr() {  
  19.         return err;  
  20.     }  
  21.   
  22.     public void setErr(List<err> err) {  
  23.         this.err = err;  
  24.     }  
  25.   
  26.     public OtherDetail2 getData() {  
  27.         return data;  
  28.     }  
  29.   
  30.     public void setData(OtherDetail2 data) {  
  31.         this.data = data;  
  32.     }  
  33.   
  34.     public class OtherDetail2 {  
  35.         private List<partnerteamlist> partnerteamlist;  
  36.         private List<liketeamlist> liketeamlist;  
  37.         private List<feedbacks> feedbacks;  
  38.   
  39.         public List<liketeamlist> getLiketeamlist() {  
  40.             return liketeamlist;  
  41.         }  
  42.   
  43.         public void setLiketeamlist(List<liketeamlist> liketeamlist) {  
  44.             this.liketeamlist = liketeamlist;  
  45.         }  
  46.   
  47.         public List<feedbacks> getFeedbacks() {  
  48.             return feedbacks;  
  49.         }  
  50.   
  51.         public void setFeedbacks(List<feedbacks> feedbacks) {  
  52.             this.feedbacks = feedbacks;  
  53.         }  
  54.   
  55.         public class partnerteamlist {  
  56.             private int pteamId;  
  57.             private String ptitle;  
  58.             private Double pteamprice;  
  59.   
  60.             public int getPteamId() {  
  61.                 return pteamId;  
  62.             }  
  63.   
  64.             public void setPteamId(int pteamId) {  
  65.                 this.pteamId = pteamId;  
  66.             }  
  67.   
  68.             public String getPtitle() {  
  69.                 return ptitle;  
  70.             }  
  71.   
  72.             public void setPtitle(String ptitle) {  
  73.                 this.ptitle = ptitle;  
  74.             }  
  75.   
  76.             public Double getPteamprice() {  
  77.                 return pteamprice;  
  78.             }  
  79.   
  80.             public void setPteamprice(Double pteamprice) {  
  81.                 this.pteamprice = pteamprice;  
  82.             }  
  83.   
  84.         }  
  85.   
  86.         public class liketeamlist {  
  87.             private int lteamId;  
  88.             private String ltitle;  
  89.             private String limage;  
  90.             private Double lteamprice;  
  91.             private Double lmarketprice;  
  92.   
  93.             public int getLteamId() {  
  94.                 return lteamId;  
  95.             }  
  96.   
  97.             public void setLteamId(int lteamId) {  
  98.                 this.lteamId = lteamId;  
  99.             }  
  100.   
  101.             public String getLtitle() {  
  102.                 return ltitle;  
  103.             }  
  104.   
  105.             public void setLtitle(String ltitle) {  
  106.                 this.ltitle = ltitle;  
  107.             }  
  108.   
  109.             public String getLimage() {  
  110.                 return limage;  
  111.             }  
  112.   
  113.             public void setLimage(String limage) {  
  114.                 this.limage = limage;  
  115.             }  
  116.   
  117.             public Double getLteamprice() {  
  118.                 return lteamprice;  
  119.             }  
  120.   
  121.             public void setLteamprice(Double lteamprice) {  
  122.                 this.lteamprice = lteamprice;  
  123.             }  
  124.   
  125.             public Double getLmarketprice() {  
  126.                 return lmarketprice;  
  127.             }  
  128.   
  129.             public void setLmarketprice(Double lmarketprice) {  
  130.                 this.lmarketprice = lmarketprice;  
  131.             }  
  132.         }  
  133.   
  134.         public class feedbacks {  
  135.             private int totalcount;  
  136.             private Double totalscore;  
  137.             private List<feedbacklist> feedbacklist;  
  138.   
  139.             public int getTotalcount() {  
  140.                 return totalcount;  
  141.             }  
  142.   
  143.             public void setTotalcount(int totalcount) {  
  144.                 this.totalcount = totalcount;  
  145.             }  
  146.   
  147.             public Double getTotalscore() {  
  148.                 return totalscore;  
  149.             }  
  150.   
  151.             public void setTotalscore(Double totalscore) {  
  152.                 this.totalscore = totalscore;  
  153.             }  
  154.   
  155.             public List<feedbacklist> getFeedbacklist() {  
  156.                 return feedbacklist;  
  157.             }  
  158.   
  159.             public void setFeedbacklist(List<feedbacklist> feedbacklist) {  
  160.                 this.feedbacklist = feedbacklist;  
  161.             }  
  162.   
  163.             public class feedbacklist {  
  164.                 private String username;  
  165.                 private String comment;  
  166.                 private String createtime;  
  167.                 private Double score;  
  168.   
  169.                 public String getUsername() {  
  170.                     return username;  
  171.                 }  
  172.   
  173.                 public void setUsername(String username) {  
  174.                     this.username = username;  
  175.                 }  
  176.   
  177.                 public String getComment() {  
  178.                     return comment;  
  179.                 }  
  180.   
  181.                 public void setComment(String comment) {  
  182.                     this.comment = comment;  
  183.                 }  
  184.   
  185.                 public String getCreatetime() {  
  186.                     return createtime;  
  187.                 }  
  188.   
  189.                 public void setCreatetime(String createtime) {  
  190.                     this.createtime = createtime;  
  191.                 }  
  192.   
  193.                 public Double getScore() {  
  194.                     return score;  
  195.                 }  
  196.   
  197.                 public void setScore(Double score) {  
  198.                     this.score = score;  
  199.                 }  
  200.   
  201.             }  
  202.         }  
  203.   
  204.         public List<partnerteamlist> getPartnerteamlist() {  
  205.             return partnerteamlist;  
  206.         }  
  207.   
  208.         public void setPartnerteamlist(List<partnerteamlist> partnerteamlist) {  
  209.             this.partnerteamlist = partnerteamlist;  
  210.         }  
  211.     }  
  212.   
  213.     public class err {  
  214.         private int code;  
  215.         private String msg;  
  216.   
  217.         public int getCode() {  
  218.             return code;  
  219.         }  
  220.   
  221.         public void setCode(int code) {  
  222.             this.code = code;  
  223.         }  
  224.   
  225.         public String getMsg() {  
  226.             return msg;  
  227.         }  
  228.   
  229.         public void setMsg(String msg) {  
  230.             this.msg = msg;  
  231.         }  
  232.     }  
  233. }  
package com.pztuan.entity;

import java.util.List;

public class OtherDetail {

	private int state;
	private List<err> err;
	private OtherDetail2 data;

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public List<err> getErr() {
		return err;
	}

	public void setErr(List<err> err) {
		this.err = err;
	}

	public OtherDetail2 getData() {
		return data;
	}

	public void setData(OtherDetail2 data) {
		this.data = data;
	}

	public class OtherDetail2 {
		private List<partnerteamlist> partnerteamlist;
		private List<liketeamlist> liketeamlist;
		private List<feedbacks> feedbacks;

		public List<liketeamlist> getLiketeamlist() {
			return liketeamlist;
		}

		public void setLiketeamlist(List<liketeamlist> liketeamlist) {
			this.liketeamlist = liketeamlist;
		}

		public List<feedbacks> getFeedbacks() {
			return feedbacks;
		}

		public void setFeedbacks(List<feedbacks> feedbacks) {
			this.feedbacks = feedbacks;
		}

		public class partnerteamlist {
			private int pteamId;
			private String ptitle;
			private Double pteamprice;

			public int getPteamId() {
				return pteamId;
			}

			public void setPteamId(int pteamId) {
				this.pteamId = pteamId;
			}

			public String getPtitle() {
				return ptitle;
			}

			public void setPtitle(String ptitle) {
				this.ptitle = ptitle;
			}

			public Double getPteamprice() {
				return pteamprice;
			}

			public void setPteamprice(Double pteamprice) {
				this.pteamprice = pteamprice;
			}

		}

		public class liketeamlist {
			private int lteamId;
			private String ltitle;
			private String limage;
			private Double lteamprice;
			private Double lmarketprice;

			public int getLteamId() {
				return lteamId;
			}

			public void setLteamId(int lteamId) {
				this.lteamId = lteamId;
			}

			public String getLtitle() {
				return ltitle;
			}

			public void setLtitle(String ltitle) {
				this.ltitle = ltitle;
			}

			public String getLimage() {
				return limage;
			}

			public void setLimage(String limage) {
				this.limage = limage;
			}

			public Double getLteamprice() {
				return lteamprice;
			}

			public void setLteamprice(Double lteamprice) {
				this.lteamprice = lteamprice;
			}

			public Double getLmarketprice() {
				return lmarketprice;
			}

			public void setLmarketprice(Double lmarketprice) {
				this.lmarketprice = lmarketprice;
			}
		}

		public class feedbacks {
			private int totalcount;
			private Double totalscore;
			private List<feedbacklist> feedbacklist;

			public int getTotalcount() {
				return totalcount;
			}

			public void setTotalcount(int totalcount) {
				this.totalcount = totalcount;
			}

			public Double getTotalscore() {
				return totalscore;
			}

			public void setTotalscore(Double totalscore) {
				this.totalscore = totalscore;
			}

			public List<feedbacklist> getFeedbacklist() {
				return feedbacklist;
			}

			public void setFeedbacklist(List<feedbacklist> feedbacklist) {
				this.feedbacklist = feedbacklist;
			}

			public class feedbacklist {
				private String username;
				private String comment;
				private String createtime;
				private Double score;

				public String getUsername() {
					return username;
				}

				public void setUsername(String username) {
					this.username = username;
				}

				public String getComment() {
					return comment;
				}

				public void setComment(String comment) {
					this.comment = comment;
				}

				public String getCreatetime() {
					return createtime;
				}

				public void setCreatetime(String createtime) {
					this.createtime = createtime;
				}

				public Double getScore() {
					return score;
				}

				public void setScore(Double score) {
					this.score = score;
				}

			}
		}

		public List<partnerteamlist> getPartnerteamlist() {
			return partnerteamlist;
		}

		public void setPartnerteamlist(List<partnerteamlist> partnerteamlist) {
			this.partnerteamlist = partnerteamlist;
		}
	}

	public class err {
		private int code;
		private String msg;

		public int getCode() {
			return code;
		}

		public void setCode(int code) {
			this.code = code;
		}

		public String getMsg() {
			return msg;
		}

		public void setMsg(String msg) {
			this.msg = msg;
		}
	}
}


注意上面内部类的运用。

解析:

  1. Gson gson = new Gson();  
  2. OtherDetail d = gson.fromJson(jsonString,Detail.class);//取值的时候就从父类一层一层调子类成员(重要)  
Gson gson = new Gson();
OtherDetail d = gson.fromJson(jsonString,Detail.class);//取值的时候就从父类一层一层调子类成员(重要)

若出现引用异常,请查看Java内部类设计原则。


参考网址:

http://blog.chinaunix.net/uid-23392298-id-3130177.html

http://www.tuicool.com/articles/6NVrmu

http://blog.csdn.net/rain_butterfly/article/details/38404293?utm_source=tuicool

http://blog.csdn.net/caijunjun1006/article/details/11762841

http://cache.baiducontent.com/c?m=9d78d513d9901df918b0cf281a16a6335809dc743da7c76509c3e44884152c563362f4ba577a51598fd13b275fa0131aacb22173441e3df2de8d9f4aaaeacf767cd86061671cf1104f8c04e99106729276875a9fac1be4b8f53198b9d2a5dc4353bc50127af7aacd055e&p=82759a45d6c95fb90be2966f4a5597&newp=8b2a971394934eaf58e7cd235908cc231610db2151d3d5152996&user=baidu&fm=sc&query=android+gson%BD%E2%CE%F6json&qid=9feb5d090000f0c7&p1=13

http://www.cnblogs.com/menlsh/archive/2013/05/19/3087810.html

http://cache.baiducontent.com/c?m=9d78d513d9901df918b0cf281a16a6335809dc743da7c76509c3e44884152c563362f4ba577a51598fd13b275fa0131aacb22173441e3df2de8d9f4aaaeace7871d57275671cf1104f8c04ee8c1a6d9d3dc31ab8f542a3eded3291add3cedd544ec958187a8bf38e580013dd6f874e77bcf8&p=867ecc15d9c340ac03f3c7710f4a8b&newp=8b2a9715d9c340ac04b98221164285231610db2151d3d512&user=baidu&fm=sc&query=android+gson%BD%E2%CE%F6json&qid=ccc8df3d0001a1b9&p1=4

http://cache.baiducontent.com/c?m=9d78d513d9901df918b0cf281a16a6335809dc743da7c76509c3e44884152c563362f4ba577a51598fd13b275fa0131aacb22173441e3df2de8d9f4aaae8d0717fcf6623706bd71c4dce4af39d06789a76875a9fac1ce6b0f73984aea4d0c85425c944050ddab6d404&p=9f7d8f0c85cc43b408e2947d0d64cf&newp=9257df15d9c342af1fbe9b7c7f07cf231610db2151d0d11138&user=baidu&fm=sc&query=android+gson%BD%E2%CE%F6json&qid=ccc8df3d0001a1b9&p1=8



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值