Skip to content

Instantly share code, notes, and snippets.

@nielsutrecht
Created August 29, 2014 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nielsutrecht/0f10851f4b7fb7c8a3ab to your computer and use it in GitHub Desktop.
Save nielsutrecht/0f10851f4b7fb7c8a3ab to your computer and use it in GitHub Desktop.
Reading / writing JSON example
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);
}
}
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;
}
}
[ {
"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