Created
August 29, 2014 08:04
-
-
Save nielsutrecht/0f10851f4b7fb7c8a3ab to your computer and use it in GitHub Desktop.
Reading / writing JSON example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package monster; | |
import java.io.File; | |
import java.io.IOException; | |
import java.util.Arrays; | |
import java.util.List; | |
import org.codehaus.jackson.map.ObjectMapper; | |
import org.codehaus.jackson.map.SerializationConfig; | |
public class DataReaderWriter { | |
private static final File MONSTER_FILE = new File("src/test/resources/monsters.json"); | |
private final ObjectMapper _mapper; | |
public DataReaderWriter() { | |
_mapper = new ObjectMapper(); | |
_mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT); //Enable pretty printing of JSON | |
} | |
public void writeMonsters(final List<Monster> monsters) throws IOException { | |
_mapper.writeValue(MONSTER_FILE, monsters); | |
} | |
public List<Monster> readMonsters() throws IOException { | |
final Monster[] monsterArray = _mapper.readValue(MONSTER_FILE, Monster[].class); | |
return Arrays.asList(monsterArray); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package monster; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Monster { | |
private String _name; | |
private int _hitpoints; | |
private final List<String> _inventory; | |
public Monster() { | |
_inventory = new ArrayList<>(); | |
} | |
public Monster(final String name, final int hitpoints) { | |
this(); | |
_name = name; | |
_hitpoints = hitpoints; | |
} | |
public String getName() { | |
return _name; | |
} | |
public void setName(final String name) { | |
_name = name; | |
} | |
public int getHitpoints() { | |
return _hitpoints; | |
} | |
public void setHitpoints(final int hitpoints) { | |
_hitpoints = hitpoints; | |
} | |
public List<String> getInventory() { | |
return _inventory; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ { | |
"inventory" : [ "Rat hairs" ], | |
"hitpoints" : 10, | |
"name" : "Rat" | |
}, { | |
"inventory" : [ "Leather shield", "Rusted sword" ], | |
"hitpoints" : 50, | |
"name" : "Goblin" | |
} ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment