• Gson使用技巧


    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() 
  • 相关阅读:
    js 提示框的实现---组件开发之(一)
    js 原型链
    js 哈希路由原理实现
    js 弹窗的实现
    js 滑动门的实现
    Delphi IDFtp用法,包含断点续传
    memortstream Base64编码和filestream base64编码不同
    Delphi另一个多线程函数:BeginThread用法
    delphi 讲的比较详细的多线程(推荐)
    多线程简单实用
  • 原文地址:https://www.cnblogs.com/ylz8401/p/7264493.html
Copyright © 2020-2023  润新知