Text Adventure Time! (Loading Objects From JSON)

Some time ago, when I was brushing off my Java, I wanted to get my hands dirty while making something fun. I LOVE text adventure RPGs, so that’s what I attempted to build.

This is the eighth post documenting my single user dungeon development adventure.

In my last Java Text Aventure post, I left off at commit 41eb6c4, where I introduced random room layout generation.

In this post I’ll be covering the conversion of entity file loading from CSV to JSON.

Here is the list of posts published on this project so far!

Check out the repo for this post and follow along!


Target commits:

Running the game:
(yes that pesky properties file is still there, getting in the way)
(also, pesky line endings need cleaned up with sed)

JSON is awesome

In Text Adventure Time! (Loading Objects From Text Files), we added entity loading from files using CSV. That worked just fine, but adding new entities was pretty rigid. All fields had to be defined, and the constructor had to be respected.

By switching to JSON objects, adding new entities is much easier. We only need to define the fields we care about, and the jackson library handles the rest.

Calling the JSON parser

The loadFile is the same, we just point to the .json rather than the .txt. We stuff it into the class variable file, create our ArrayList, then invoke the appropriate method to load the objects. Ideally this would be genericized, since most of the code is duplicated between the different object type method loads, but for now, this’ll do.

The createRooms method gets invoked when the World is built. EntityFactory is a composition parameter of World, and gets invoked through some delegation: World.buildNewWorld > World.loadEntityPools > entityFactory.createRooms();.

Loading the objects from the JSON files

To load the objects from the JSON file, createRooms calls parseRoomJson, which uses the jackson ObjectMapper. ObjectMapper.readVaule takes a File object and a TypeFactory. We pass List.class and Room.class to TypeFactory.constructCollectionType to tell it what kind of collection (a List) of what kind of object (Room) to build.


Adding new rooms

Now if we want to add a Room to the pool of Rooms which is used by the World class, we just add a line to the JSON file /src/main/resources/entityRepository/Room.json, and when the game loads, the new room will be used in the layout generation.

So much more explicit. And the order doesn’t matter!

Try replacing the Room.json file contents with a couple of rooms of your own. Then build the game with the gradle wrapper and run it to see your rooms!

Change the Room.json file contents to this:

Then build and run the game:

It looks like we got an endless loop of two rooms!

Matthew Odle

Indie dev, autodidactic polyglot, lover of programming, dad, musician, writer, mentor

One thought on “Text Adventure Time! (Loading Objects From JSON)

Join the Discussion