Deserializing with GSON

For a project I’ve been working on I needed to deserialize a number of objects from JSON and because I’m lazy I wanted something that would let me do that easily. I came across GSON, and was very impressed with how easy it was to use.

Here’s some of my JSON;

    "intro": "An introduction",
    "yesResponse": "Player said yes",
    "yesEffect": -10,
    "noResponse": "Player said no",
    "noEffect": 10

Here’s the class that I want to deserialize it to;

    private final String intro;
    private final String yesResponse;
    private final int yesEffect;
    private final String noResponse;
    private final int noEffect;

    public Event(final String intro, final String yesResponse, 
final int yesEffect, final String noResponse, final int noEffect) {
        this.intro = intro;
        this.yesResponse = yesResponse;
        this.yesEffect = yesEffect;
        this.noResponse = noResponse;
        this.noEffect = noEffect;

Here’s the code required to make it happen;

        String jsonString = new String(Files.readAllBytes(path));
        Gson gson = new Gson();
        Event[] events = gson.fromJson(jsonString, Event[].class);

Nice and simple!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s