1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
package net.sowgro.npehero.main;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.*;
/**
* An ergonomic JSON API wrapper inspired by the Bukkit YAML API
*/
public class JSONFile {
private final File file;
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode writeNode = objectMapper.createObjectNode();
JsonNode readNode;
public JSONFile(File file) {
try {
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
this.file = file;
}
public String getString(String key, String def) {
if (!readNode.has(key)) {
return def;
}
return readNode.get(key).asText();
}
public int getInt(String key, int def) {
if (!readNode.has(key)) {
return def;
}
try {
return Integer.parseInt(readNode.get(key).asText());
}
catch (NumberFormatException e) {
return def;
}
}
public double getDouble(String key, double def) {
if (!readNode.has(key)) {
return def;
}
try {
return Double.parseDouble(readNode.get(key).asText());
}
catch (NumberFormatException e) {
return def;
}
}
public boolean getBoolean(String key, boolean def) {
if (!readNode.has(key)) {
return def;
}
try {
return Boolean.parseBoolean(readNode.get(key).asText());
}
catch (NumberFormatException e) {
return def;
}
}
public void set(String key, String value) {
if (value == null) {
return;
}
writeNode.put(key, value);
}
public void set(String key, int value) {
writeNode.put(key, value);
}
public void set(String key, double value) {
writeNode.put(key, value);
}
public void set(String key, boolean value) {
writeNode.put(key, value);
}
public boolean containsKey(String key) {
return writeNode.has(key);
}
public void read() throws Exception {
if (file.length() == 0) {
readNode = objectMapper.createObjectNode();
return;
}
readNode = objectMapper.readTree(file);
}
public void write() throws IOException {
objectMapper.writeValue(file, writeNode);
}
}
|