【问题标题】:How to convert null string to empty string in retrofit2?如何在retrofit2中将空字符串转换为空字符串?
【发布时间】:2016-10-12 09:15:20
【问题描述】:

在改用 retrofit2 之前,我使用的是 volley。为了设置我的 pojo 值,我使用 optString 和 optInt 从 JSONObject 响应中检索值。这会将我的空字符串替换为空字符串,我不需要添加空检查。如何对改造 2 做同样的事情。

Json 示例:

{
company_name : null
}

Pojo 类

public class company implements Serializable{
@SerializedName("company_name")
private String companyName;

public String getCompanyName(){
return companyName;
}

public void setCompanyName(String companyName){
this.companyName = companyName;
}

String companyName = getCompany(); 导致 NullPointerException。

有没有办法将每个空字符串转换为空字符串,如 optString.?

【问题讨论】:

    标签: retrofit2


    【解决方案1】:

    使String 类型的适配器类似

    public class StringAdapter extends TypeAdapter<String> {
         public String read(JsonReader reader) throws IOException {
           if (reader.peek() == JsonToken.NULL) {
             reader.nextNull();
             //here is the point of interest
             //instead of return null;
             return "";
           }
           return reader.nextString();
    
         }
         public void write(JsonWriter writer, String value) throws IOException {
           if (value == null) {
             writer.nullValue();
             return;
           }
           writer.value(value);
         }
       }
    

    更多详情请阅读this

    【讨论】:

      【解决方案2】:

      大概是这样的;使用的三元运算符与if相同:

      public void setCompanyName(String value){
        this.companyName = (value==null ? "" : value);
      }
      

      或尝试使用@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) 注释的Jackson Converter 类似JsonParserUtil.toPojo(...),那么不应该传递任何NULL 值——而setter 仍然会在NULL 值上崩溃,除非经过适当清理。

      【讨论】:

      • 是的,这是一种可能的解决方案,但我有很多 POJO,并且在每个 POJO 中为每个字段执行此操作是一项耗时的任务。我正在寻找更简单的方法来做同样的事情。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      • 2014-11-12
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      相关资源
      最近更新 更多