moshi:解析假设为整数的空值

ryoqjall  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(473)

我有一节课

public class Data{
   int integer_value = 0;
}

然后我从服务器上得到了json {"integer_value":null} 当我试图用

String json = "{\"integer_value\":null}"
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<Data> jsonAdapter = moshi.adapter(Data.class);
Data data = jsonAdapter.fromJson(json);

它将引发异常:

Caused by: com.squareup.moshi.JsonDataException: Expected an int but was NULL at path $.integer_value

我怎样才能防止这种情况?我希望它好像“整数值”是缺席。因此,它将使用默认值0。

suzh9iv8

suzh9iv81#

这里有一种方法:(略)

public class Test {
    public static void main(String args[]) throws IOException {
        String json = "{\"integer_value\":null}";
        Moshi moshi = new Moshi.Builder().add(new ZeroWhenNullAdapter()).build();
        JsonAdapter<Data> jsonAdapter = moshi.adapter(Data.class);
        Data data = jsonAdapter.fromJson(json);
    }
}

@Retention(RetentionPolicy.RUNTIME)
public @interface Nullable { // you can use any annotation named 'Nullable'
}

@Retention(RUNTIME)
@JsonQualifier
public @interface ZeroWhenNull {}

public class Data {
    @ZeroWhenNull
    int integer_value = 0;
}

public class ZeroWhenNullAdapter {
    // this isn't really needed, but Moshi insists that adapters work both
    // ways as far as I can tell
    @ToJson
    String toJson(@ZeroWhenNull int n) {
        return Integer.toString(n);
    }

    @FromJson
    @ZeroWhenNull
    int fromJson(@Nullable String n) {
        return n == null ? 0 : Integer.parseInt(n);
    }
}

这不是使用默认值,而是显式地将字段设置为零。

相关问题