美文网首页
Gson 嵌套数据的任意获取

Gson 嵌套数据的任意获取

作者: 舍是境界 | 来源:发表于2020-11-12 19:55 被阅读0次

    背景

    最近公司在整fastjson转gson,发现一些问题,比如空值判断,然后整了一个工具出来,支持任意数据嵌套的查询,其他类型同理,这里直接贴出代码:

    代码

    package com.cwg.codecomplete.utils;
    
    import com.google.gson.JsonElement;
    import com.google.gson.JsonObject;
    import lombok.experimental.UtilityClass;
    
    import java.util.Arrays;
    
    /**
     * 创建时间:2020-11-12 19:42
     * gson获取任意json数据,这里写一个demo,支持多层级嵌套json
     *
     * @author rooter
     **/
    @UtilityClass
    public class GsonUtil {
    
        public static String getAsString(JsonObject jsonObject, String... names){
            JsonElement jsonElement = getJsonElement(jsonObject, names);
            if(jsonElement != null){
                return jsonElement.getAsString();
            }
    
            return null;
        }
    
        public static JsonObject getAsJsonObject(JsonObject jsonObject, String... names){
            JsonElement jsonElement = getJsonElement(jsonObject, names);
            if(jsonElement != null){
                return jsonElement.getAsJsonObject();
            }
    
            return null;
        }
    
        private JsonElement getJsonElement(JsonObject jsonObject, String... names){
            if(jsonObject == null || names.length ==0 ){
                return null;
            }
    
            JsonObject jsonSub = jsonObject;
            if(names.length > 1){
                jsonSub = getAsJsonObject(jsonObject, Arrays.copyOf(names, names.length - 1));
            }
    
            if(jsonSub == null){
                return null;
            }
    
            JsonElement jsonElement = jsonSub.get(names[names.length - 1]);
    
            return jsonElement;
        }
    }
    
    
    

    使用

    package com.cwg.codecomplete.utils;
    
    import com.google.gson.Gson;
    import com.google.gson.JsonObject;
    import org.junit.Assert;
    import org.junit.Before;
    import org.junit.Test;
    
    /**
     * 创建时间:2020-11-12 19:57
     *
     * @author rooter
     **/
    public class GsonUtilTest {
    
        JsonObject jsonObject;
        @Before
        public void setUp(){
            String json = "{\"subscriptions\":{\"id\":14,\"source_type\":\"Collection\",\"name\":\"@IT·互联网\",\"avatar_source\":\"https://upload.jianshu.io/collections/images/14/6249340_194140034135_2.jpg\",\"unread_count\":100},\"page\":1,\"total_pages\":1}";
            jsonObject = new Gson().fromJson(json, JsonObject.class);
    
        }
    
        @Test
        public void getAsString() {
            Assert.assertEquals("@IT·互联网", GsonUtil.getAsString(jsonObject, "subscriptions", "name"));
        }
    }
    
    

    总结

    欢迎大家讨论完善

    相关文章

      网友评论

          本文标题:Gson 嵌套数据的任意获取

          本文链接:https://www.haomeiwen.com/subject/fpapbktx.html