Gson fromJson() 用法

Posted Reboost

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Gson fromJson() 用法相关的知识,希望对你有一定的参考价值。

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() 用法的主要内容,如果未能解决你的问题,请参考以下文章

Gson 使用总结 高级用法

gson的特殊用法

Json数据交换一Gson

Gson.fromJson没有处理错误的响应

如何解决gson.fromJson()在android中有错误

Gson fromJson 在 Proguard 之后返回 null