1. 程式人生 > >Gson fromJson() 用法

Gson fromJson() 用法

名與字 通過 clas gets json數據 array body lse end

1.純數組JSON

字符串轉換

[ {"name": "zhangsan","age": "10","phone": "11111","email": "[email protected]"},

{"name": "lisi","age": "20","phone": "22222","email": "[email protected]"},

...]

解析代碼如下:

public class UserBean {

//變量名跟JSON數據字段名必須一致

private String name ;

private String age;

private String phone;

private String email;

...

}

//拿到本地JSON 並轉成String

String strByJson = ConstructTestJsonStr();//此處函數內容省略

//Json的解析類對象

JsonParser parser = new JsonParser();

//將JSON的String 轉成一個JsonArray對象

JsonArray jsonArray = parser.parse(strByJson).getAsJsonArray();

Gson gson = new Gson();

ArrayList<UserBean> userBeanList = new ArrayList<>();

//加強for循環遍歷JsonArray

for (JsonElement user : jsonArray) {

//使用GSON,直接轉成Bean對象

UserBean userBean = gson.fromJson(user, UserBean.class);

userBeanList.add(userBean);

}

2.有數據頭的純數組

數據轉換

{"muser": [{"name": "zhangsan","age": "10","phone": "11111","email": "[email protected]"},
           {"name": "lisi","age": "20","phone": "22222","email": "[email protected]"},


...]
}

//解析有數據頭的純數組

//拿到本地JSON 並轉成String

String strByJson = ConstructTestJsonStr();//此處函數內容省略;

//先轉JsonObject

JsonObject jsonObject = new JsonParser().parse(strByJson).getAsJsonObject();

//再轉JsonArray 加上數據頭

JsonArray jsonArray = jsonObject.getAsJsonArray("muser");

Gson gson = new Gson();

ArrayList<UserBean> userBeanList = new ArrayList<>();

//循環遍歷

for (JsonElement user : jsonArray) {

//通過反射 得到UserBean.class

UserBean userBean = gson.fromJson(user, new TypeToken<UserBean>() {}.getType());

userBeanList.add(userBean);

}

3.有數據頭的復雜

數據轉換

{ "code": 200,"msg": "OK",
 "muser": [{"name": "zhangsan","age": "10","phone": "11111","email":"[email protected]"},
           {"name": "lisi","age": "20","phone": "22222","email": "[email protected]"},
           ...]
}

被解析對象不是純數組數據,還有其它字段+數組(含頭),方法如下:

根據 JSON 建立Bean,註意這裏的 Bean 是返回所有字段,因為 GSON 能直接解析成 List ,所以 Bean 是下面這樣的,同樣把占地方的get/set省略:

public class ResultBean {
    //註意變量名與字段名必須一致
    private int code;
    private String msg;
    private List<UserBean> muser;
    public class UserBean{
        private String name ;
        private String age;
        private String phone;
        private String email;
        ...
    }
    ...
}
//有消息頭 復雜數據 常規方式 方法如下
//拿到Json字符串
String strByJson =  ConstructTestJsonStr();//此處函數內容省略;
//GSON直接解析成對象
ResultBean resultBean = new Gson().fromJson(strByJson,ResultBean.class);
//對象中拿到集合
List<ResultBean.UserBean> userBeanList = resultBean.getMuser();
三句話搞定,由此看出GSON的強大

4.只解析復雜JSON中的

數組或數組中的某部分內容

有數據頭 復雜數據 截取方式,如對第3例中JSON數據內容只想取“muser”數組中年齡(age)大於30歲的怎麽辦?

方法1:全部解析,再從 List 中取。(但假如有1萬條數據?全部解析太麻煩),方法2:條件遍歷!(以下代碼示例):

//解析代碼:

//拿到JSON字符串

String strByJson = ConstructTestJsonStr();//此處函數內容省略;

List<UserBean> userBeanList = new ArrayList<>();

//拿到數組

JsonObject jsonObject = new JsonParser().parse(strByJson).getAsJsonObject();

JsonArray jsonArray = jsonObject.getAsJsonArray("muser");

//循環遍歷數組

for (JsonElement user : jsonArray) {

UserBean userBean = new Gson().fromJson(user, new TypeToken<UserBean>() {

}.getType());

//根據條件過濾

if (Integer.parseInt(userBean.getAge()) > 30) {

userBeanList.add(userBean);

}

}

5.嵌套超復雜JSON

數據轉換

三種方式:1,全部解析出來;2,要什麽解析什麽;3,JsonReader,第1/2招前述已解釋,下面示例JsonReader(類似逐節點解釋XML)

//通過JsonReader的方式去解析

private void parseComplexJArrayByReader() throws IOException {

String strByJson = JsonToStringUtil.getStringByJson(this, R.raw.juser_4);

JsonReader reader = new JsonReader(new StringReader(strByJson));

try {

reader.beginObject();

String tagName = reader.nextName();

if (tagName.equals("group")) {

//讀group這個節點

readGroup(reader);

}

reader.endObject();

} finally {

reader.close();

}

}

//讀group這個節點

private void readGroup(JsonReader reader) throws IOException {

reader.beginObject();

while (reader.hasNext()) {

String tagName = reader.nextName();

if (tagName.equals("user")) {

readUser(reader);

} else if (tagName.equals("info")) {

readInfo(reader);

}

}

reader.endObject();

}

//讀用戶基本消息 user節點

private void readUser(JsonReader reader) throws IOException {

reader.beginObject();

while (reader.hasNext()) {

String tag = reader.nextName();

if (tag.equals("name")) {

String name = reader.nextString();

nameText.setText(name);

} else if (tag.equals("age")) {

String age = reader.nextString();

ageText.setText(age);

}

...

else {

reader.skipValue();//忽略

}

}

reader.endObject();

}

//讀用戶其他消息 info節點

private void readInfo(JsonReader reader) throws IOException {

reader.beginObject();

while (reader.hasNext()) {

String tag = reader.nextName();

if (tag.equals("address")) {

String address = reader.nextString();

addressText.setText(address);

} else if (tag.equals("work")) {

String work = reader.nextString();

workText.setText(work);

}

...

else {

reader.skipValue();//忽略

}

}

reader.endObject();

}

6.簡單數據+LIST+MAP

轉換

public class Student {

public int id;

public String nickName;

public int age;

public ArrayList<String> books;

public HashMap<String, String> booksMap;

}

Student student = new Student();

student.id = 1;

student.nickName = "Jack";

student.age = 22;

student.email = "[email protected]";

ArrayList<String> books = new ArrayList<String>();

books.add("數學");

books.add("語文");

books.add("英語");

books.add("物理");

books.add("化學");

books.add("生物");

student.books = books;

HashMap<String, String> booksMap = new HashMap<String, String>();

booksMap.put("1", "數學");

booksMap.put("2", "語文");

booksMap.put("3", "英語");

booksMap.put("4", "物理");

booksMap.put("5", "化學");

booksMap.put("6", "生物");

student.booksMap = booksMap;

Gson gson = new Gson();

String result = gson.toJson(student);

Student studentG = gson.fromJson(result, Student.class);

Log.e("MainActivity", "id:" + studentG.id);

Log.e("MainActivity", "nickName:" + studentG.nickName);

Log.e("MainActivity", "age:" + studentG.age);

Log.e("MainActivity", "email:" + studentG.email);

Log.e("MainActivity", "books size:" + studentG.books.size());

Log.e("MainActivity", "booksMap size:" + studentG.booksMap.size());

打印輸出

id:1

nickName: Jack

age:22

email:[email protected]

books size:6

booksMap size:6

7.把List或者Map等集合

的泛型換成自定義個class

泛型定義

public HashMap<String,Book> booksMap;

public class Book{

public int id;

public String name;

}

HashMap<String, Book> booksMap = gson.fromJson(result, new TypeToken<HashMap<String, Book>>() { }.getType());

Gson gson = new Gson();

HashMap<String, Book> booksMap = new HashMap<>();

booksMap.put("book1", new Book(1, "Java基礎開發"));

booksMap.put("book2", new Book(2, "Java設計模式"));

booksMap.put("book3", new Book(3, "Java算法"));

String dataStr = gson.toJson(booksMap);

System.out.println("dataStr:" + dataStr);

HashMap<String, Book> booksMap2 = gson.fromJson(dataStr, new TypeToken<HashMap<String, Book>>() {

}.getType());

for (Map.Entry<String, Book> entry : booksMap2.entrySet()) {

System.out.println("key:"+entry.getKey() + " value:" + entry.getValue().toString());

}

輸出結果

dataStr:{"book2":{"id":2,"name":"Java設計模式"},"book1":{"id":1,"name":"Java基礎開發"},"book3":{"id":3,"name":"Java算法"}}

key:book2 value:Book{id=2, name=‘Java設計模式‘}

key:book1 value:Book{id=1, name=‘Java基礎開發‘}

key:book3 value:Book{id=3, name=‘Java算法‘}

Gson fromJson() 用法