This blog post describes how to create an Item database using libgdx JSON parser and storing it in a Collections object to retrieve from.
0.) Create the JSON file
Save this as "weaponDb.json". This JSON object is used to create a list of Items in which we can grab items from.[ { "id": 1, "name": "Dumb Basic Sword", }, { "id": 2, "name": "Bad Ass Flaming Sword", }, { "id": 3, "name": "Sword of Kick Ass", } ]
1.) Create the test
A simple JUnit test to test our databaseimport com.mygdx.items.Item; import com.mygdx.items.ItemLoader; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; /*Simple Test Case*/ public class TestDb { @Test public void testDb() throws IOException { ItemLoader itemLoader = new ItemLoader(); ArrayList- database = itemLoader.load("weaponDb.json"); for (Item item : database) { assert item.getName != null; System.out.println(item.getName()); } } }
2.) Create the ItemLoader
This class converts JSON objects to Java objects.import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonWriter; import java.util.ArrayList; public class ItemLoader { public ArrayList- load(String db) { //Persist JSON object in a Collection, in my case an ArrayList ArrayList
- itemArrayList = new ArrayList
- (); //Setup JSON requirements Json json = new Json(); json.setTypeName(null); json.setUsePrototypes(false); json.setIgnoreUnknownFields(true); json.setOutputType(JsonWriter.OutputType.json); //Convert each JSON obj to an Weapon obj for (Object obj : json.fromJson(ArrayList.class, Weapon.class, new FileHandle(db))) { itemArrayList.add((Weapon) obj); } return itemArrayList; } }
3.) Creating the Item Interface
The Item interface allows a player to equip different types of items that implements the Item interface. Can be armor, weapons, or accessories.public interface Item { public int getId(); public String getName(); }
4.) Create the Weapon class
This weapon class extends the Item interface. If you want to create a Armor Object just implement the Item interface when creating you armor database.public class Weapon implements Item { private int id; private String name; public int getId() { return id; } public String getName() { return name; } }
Comments
Post a Comment