码迷,mamicode.com
首页 > 其他好文 > 详细

Gson用法

时间:2020-06-17 01:40:13      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:build   weight   新建   null   code   default   one   class   static   

记录下最近对Gson的使用方法,待完善。。

?

1. 创建一个Gson对象

Gson gson = new GsonBuilder().serializeNulls().create();

serializeNulls():序列化null值字段,因为Gson默认不序列化空值:

Configure Gson to serialize null fields. By default, Gson omits all fields that are null during serialization.

?

2. 解析示例

String str = "{"apple":{"weight":12,"color":"red"},"people":{"name":"xiaoming","age":18}}"

?

方法一: 解析成JSONObject形式

JsonObject o = gson.fromJson(str, JsonObject.class);
JsonElement element = o.get("people");
JsonElement element1 = o.get("apple");
People people1 = gson.fromJson(element, People.class);
Apple apple1 = gson.fromJson(element1, Apple.class);

?

方法二:解析成新JavaBean

新建JavaBean:BianTai.java

注意:如果JavaBean的字段名与Json字符串的键名不一样需要@SerializedName("json键名")来指定值的反序列化

@Data
@ToString
public class BianTai {

    private Apple apple;
    @Data
    private static class Apple{
        private Integer weight;
        private String color;
    }

    private People people;
    @Data
    private static class People{
        private String name;
        private Integer age;
    }
}

直接解析成BianTai

BianTai bianTai = gson.fromJson(str, BianTai.class);

结果

BianTai(apple=BianTai.Apple(weight=12, color=null), people=BianTai.People(name=xiaoming, age=18))

Gson用法

标签:build   weight   新建   null   code   default   one   class   static   

原文地址:https://www.cnblogs.com/guaosky/p/13149920.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!