Question

I have a class with some int parameters and I'm trying to load some value into this class by using fromJson. It works well when the parameters are natural numbers but throws exception when the parameters are not natural.

Code example:

public class WebElemetsPoss{
    int screenWidth;
    int screenHeight;
    ...
}

Gson gson = new Gson();
// value = {"screenWidth":360,"screenHeight":519.894, .... }
WebElemetsPoss wep = gson.fromJson(value, WebElemetsPoss.class);

Is there a way to perform auto-cast from double to int while using fromJson?

Was it helpful?

Solution

The easiest way to get the result is using some helper class:

public class WebElemetsPoss {
    int screenWidth;
    int screenHeight;

    public WebElemetsPoss(double screenWidth, double screenHeight) {
        this.screenWidth = (int)screenWidth;
        this.screenHeight = (int)screenHeight;
    }

    public WebElemetsPoss(DoubleLoader loader) {
        this(loader.screenWidth, this.screenHeight);
    }

    public static class DoubleLoader {
        double screenWidth;
        double screenHeight;
    }
}

....

Gson gson = new Gson();
WebElemetsPoss wep = new WebElemetsPoss(gson.fromJson(value, WebElemetsPoss.DoubleLoader.class));

The other possible solution is to add the custom type adapter:

class WebElemetsPossAdapter extends TypeAdapter<WebElemetsPoss> {
    @Override
    public WebElemets read (JsonReader reader) throws IOException {
        int screenWidth = 0, screenHeight = 0;
        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            if (name.equals("screenWidth")) {
                screenWidth = (int)reader.nextDouble();
            } else if (name.equals("screenHeight")) {
                screenHeight = (int)reader.nextDouble();
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
        return new WebElemets(screenWidth, screenHeight);
    }

    @Override
    public void write(JsonWriter out, WebElemets value) throws IOException {
    }
}

//...

Gson gson = new GsonBuilder().registerTypeAdapter(WebElemetsPoss.class, new WebElemetsPossAdapter()).create();
//...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top