octavio
octavio

Reputation: 486

GSON deserialize string to two integers

I am in a situation where I have to parse the following JSON:

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

I know that maj and min will always be of integer-type so the class I am parsing to has both these fields as integers:

public int maj;
public int min;

How can I get GSON to give the "maj:min" field special treatement and parse it accordingly while deserializing?

Upvotes: 1

Views: 1136

Answers (1)

Bertrand Martel
Bertrand Martel

Reputation: 45372

Build the model for your custom field :

public class CustomHour {

    public int maj;
    public int min;

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

Build the deserializer for this custom class :

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);
    }
}

Build your Data class that embed the custom field (with the field name) :

public class Data {

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

Register CustomHourDeserializer as type adapter before deserializing :

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);

Upvotes: 3

Related Questions