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
JsonObject content = new JsonParser().parse(response).getAsJsonObject();
int status =content.get("status").getAsInt();
if (status != 200)
throw new Exception("加载meta信息出现异常,status:" + status);
for (JsonElement jsonElement : content.get("result").getAsJsonArray()) {
JsonObject item = jsonElement.getAsJsonObject();
StorageInfo storage = new StorageInfo();
String namespace = item.get("namespace").getAsString().toLowerCase();
storage.setStorageName(item.get("storageName").getAsString());
storage.setStorageType(StorageType.fromId(item.get("storageType").getAsInt()));
result.put(namespace, storage);
}
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()