首页 > 技术文章 > Gson使用技巧

ylz8401 2017-07-31 18:03 原文

1. CharMatcher

String serviceUrl = CharMatcher.is('/').trimTrailingFrom(ConfigHelper.metaServiceUrl()) + "/storage/query?appid=" + ConfigHelper.appId() + "&feature=1";

 

2. Precondition

Preconditions.checkArgument(!Strings.isNullOrEmpty(namespace), "参数namespace不能为空");

 

3. JsonParser

 1 JsonObject content = new JsonParser().parse(response).getAsJsonObject();
 2 int status =content.get("status").getAsInt();
 3 if (status != 200)
 4     throw new Exception("加载meta信息出现异常,status:" + status);
 5 for (JsonElement jsonElement : content.get("result").getAsJsonArray()) {
 6     JsonObject item = jsonElement.getAsJsonObject();
 7     StorageInfo storage = new StorageInfo();
 8     String namespace = item.get("namespace").getAsString().toLowerCase();
 9     storage.setStorageName(item.get("storageName").getAsString());
10     storage.setStorageType(StorageType.fromId(item.get("storageType").getAsInt()));
11     result.put(namespace, storage);
12 }

 

4. Strings

Strings.isNullOrEmpty(namespace)

 

5. 对于bean 中有部分属性需要忽略

解决方案:(使用ExclusionStrategy)

创建注解类 Exclude

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Exclude {
}

在gson中配置 忽略带有Exclude的属性:

Gson gson = new GsonBuilder()
                .setExclusionStrategies(new ExclusionStrategy(){
                @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getAnnotation(Exclude.class) != null;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
})

使用时在需要忽略的属性上标记@Exclude 即可:

class Mock{
    String name;
    String age;
    @Exclude
    String gender;
}

 ------------------------

指定哪些是要暴露转换的属性

@Expose  
private Integer businessId;  

但这个时候要用

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
BusinessSystem bus = (BusinessSystem) (gson.fromJson(data,
BusinessSystem.class));

 

 

6. 自定义序列化字段名字

@SerializedName("email_address")
public String emailAddress;

 

7. 泛型在Gson中的使用

//数组
String jsonss = "[\"aa\",\"bb\",\"cc\"]";  
String[] ss = gson.fromJson(jsonss, String[].class);  
for (String s:ss) {  
      Log.i(TAG,s);  
}  
String s = gson.toJson(ss);  
Log.i(TAG,s);

//List
List<String> list=gson.fromJson(jsonss, new TypeToken<List<String>>() {}.getType());
List<User> list=gson.fromJson(jsonss, new TypeToken<List<User>>() {}.getType());
//也就是说,GSON把json转换为JAVA泛型对象的时候,要先定义好
//Type collectionType = new TypeToken<GenericModel<Integer>>(){}.getType() 

 

推荐阅读