Gson 的 使用(toJson 和 fromJson )
发布日期:2021-06-30 08:02:18 浏览次数:3 分类:技术文章

本文共 1325 字,大约阅读时间需要 4 分钟。

使用Gson 首选需要 引入Gson 库 ,这个可以在github 上搜索Gson 查看最近的版本的即可

Gson 里面有2个方法 toJson 和fromJson 

toJson 是把字符串转成  json 形式

fromJson 是把json 形式转成字符串形式

下面列举下用法

1 toJson 这个常用在我们单独打印某个请求接口上传后台数据 全部打印出来

Map
map = new HashMap<>(); map.put("name", "小牧"); map.put("age", "23"); map.put("hobby", "游戏"); String json = new Gson().toJson(map); System.out.print(json);

打印结果

{"name":"小牧","age":"23","hobby":"游戏"}

这样就完了 简单的很

然后写fromJson 把这个json 字符串放到一个Bean里面,设置set,get方法 如下

public class PeopleBean {    /**     * name : 小牧     * age : 23     * hobby : 游戏     */    private String name;    private String age;    private String hobby;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getAge() {        return age;    }    public void setAge(String age) {        this.age = age;    }    public String getHobby() {        return hobby;    }    public void setHobby(String hobby) {        this.hobby = hobby;    }}

然后就是我们经常请求接口解析的数据了如下

String result = "{\"name\":\"小牧\",\"age\":\"23\",\"hobby\":\"游戏\"}";        PeopleBean bean = new Gson().fromJson(result, PeopleBean.class);        System.out.print(bean.getName());        System.out.print(bean.getAge());        System.out.print(bean.getHobby());

就简单的说这2个方法把,也是经常使用到的方法。。。。

转载地址:https://huxiaomu.blog.csdn.net/article/details/100351938 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Json 知识学习
下一篇:字符串转 Json 数组

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月29日 02时01分27秒