您的 JSON 文件无效。您只有几个 JSON 对象,但您需要将它们捆绑在一个 JSON 数组中,如下所示:
[
{
"name": "John",
"country": "gr",
"features": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.7123809523809526,
0.75,
0.0
],
"timestamp": 1637924593676
},
{
"name": "Scott",
"country": "gb",
"features": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.6598639455782312,
0.2,
0.15601209271073035
],
"timestamp": 1637924610010
},
{
"name": "Michael",
"country": "it",
"features": [
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.6877551020408165,
0.75,
0.06856164464370273
],
"timestamp": 1638458784201
}
]
为了修正你的写作方法,你需要为它提供一个MyClass对象的列表,而不是一次一个(你不需要在使用这个解决方案写作时追加):
public class Main {
public static void main(String[]args) throws IOException {
List<MyClass> objectsToSerialize = new ArrayList<>();
objectsToSerialize.add(new MyClass("Name1", "Country1", new double[] { 1.0 }));
objectsToSerialize.add(new MyClass("Name2", "Country2", new double[] { 2.0 }));
objectsToSerialize.add(new MyClass("Name3", "Country3", new double[] { 3.0 }));
ObjectMapper mapper = new ObjectMapper();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myclass.json")));
mapper.writeValue(out, objectsToSerialize);
}
}
这意味着您的方法必须接受MyClass 的列表,而不是单个MyClass:
private static void writeJSON(List<MyClass> objectsToSerialize) throws IOException {
ObjectMapper mapper = new ObjectMapper();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myclass.json")));
mapper.writeValue(out, objectsToSerialize);
}
如果您需要不断地向 JSON 文件添加内容,您可以执行以下操作:
public class Main {
public static void main(String[]args) throws IOException {
// Read the file
List<MyClass> myClasses = readFromFile();
// Add whatever MyClass objects you want to the read List
myClasses.add(new MyClass("Name1", "Country1", new double[] { 1.0 }));
myClasses.add(new MyClass("Name2", "Country2", new double[] { 2.0 }));
myClasses.add(new MyClass("Name3", "Country3", new double[] { 3.0 }));
// Write the whole List again
writeJSON(myClasses);
}
private static List<MyClass> readFromFile() throws IOException {
String jsonString = FileUtils.readFileToString(new File("myclass.json"), StandardCharsets.UTF_8);
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(jsonString, new TypeReference<List<MyClass>>() {});
}
private static void writeJSON(List<MyClass> objectsToSerialize) throws IOException {
ObjectMapper mapper = new ObjectMapper();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myclass.json")));
mapper.writeValue(out, objectsToSerialize);
}
}