When using the following code I can read the JSON contents that you have provided. To read the file a simple InputStream
is used (this version reads using the getClass().getResourceAsStream()
approach but any type of InputStream
such as URL.openConnection()
or FileInputStream
will work the same.
public class JsonFileReader {
private Map<String, Integer> defaultValues = new HashMap<>();
public static void main(String... args) throws IOException {
final JsonFileReader reader = new JsonFileReader("/foo.json");
System.out.println(reader.getValue("cobblestone")); // -> 1
}
public JsonFileReader(String filename) throws IOException {
try (InputStream stream = getClass().getResourceAsStream(filename)) {
ObjectMapper mapper = new ObjectMapper();
final JsonNode result = mapper.readTree(stream);
for (JsonNode defaultValue : result.path("default-values")) {
defaultValues.put(
defaultValue.get("name").asText(),
defaultValue.get("value").asInt());
}
}
}
public Integer getValue(String name) {
return defaultValues.get(name);
}
}
JsonNode
and ObjectMapper
are part of the Jackson library. Jackson is a suite of data-processing tools for Java that includes a JSON parsing and generation library. Simply add the following to your pom.xml
(or similar) to get access to the proper libs:
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.3.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.3</version>
</dependency>
</dependencies>
EDIT:* The OP indicated that they did not use Java 7+. The Java 5/6-version of the try
statement looks like the very verbose code sample below.
public JsonFileReader(String filename) throws IOException {
InputStream stream = null;
try {
stream = getClass().getResourceAsStream(filename);
ObjectMapper mapper = new ObjectMapper();
final JsonNode result = mapper.readTree(stream);
for (JsonNode defaultValue : result.path("default-values")) {
defaultValues.put(
defaultValue.get("name").asText(),
defaultValue.get("value").asInt());
}
} finally {
if (stream != null) {
stream.close();
}
}
}