GSON将字符串反序列化为两个整数

时间:2017-02-19 03:11:56

标签: java json gson

我处于需要解析以下JSON的情况:

{ "maj:min": "8:80" }

我知道maj和min将始终是整数类型,所以我解析的类将这两个字段都作为整数:

public int maj;
public int min;

如何让GSON给出" maj:min"字段特殊处理并在反序列化时进行相应的解析?

1 个答案:

答案 0 :(得分:3)

为自定义字段构建模型:

public class CustomHour {

    public int maj;
    public int min;

    public CustomHour(int maj, int min) {
        this.maj = maj;
        this.min = min;
    }
}

为此自定义类构建反序列化器:

public class CustomHourDeserializer implements JsonDeserializer<CustomHour> {

    public CustomHour deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {

        String[] data = json.getAsJsonPrimitive().getAsString().split(":");
        int maj = Integer.parseInt(data[0]);
        int min = Integer.parseInt(data[1]);
        return new CustomHour(maj, min);
    }
}

构建嵌入自定义字段的Data类(使用字段名称):

public class Data {

    @SerializedName("maj:min")
    public CustomHour hour;
}

在反序列化之前将CustomHourDeserializer注册为类型适配器:

String input = "{ \"maj:min\": \"8:80\" }";
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(CustomHour.class, new CustomHourDeserializer());
Gson gson = gsonBuilder.create();
Data data = gson.fromJson(input, Data.class);
System.out.println("min : " + data.hour.min + " | max : " + data.hour.maj);