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!