I’ve been trying to figure this out for a bit but couldn’t pin-point my mistake.
I have a JSON I’d like to read into Java objects, manipulate those objects, then write them to a new JSON.
Code looks something like:
POJO
@AllArgsConstructor
@NoArgsConstructor
@Data
@ToString
public class MyPojo {
private String comment;
private long pos;
private int type;
}
Read
public List<MyPojo> readMyPojos(File srcFile) {
List<MyPojo> jsonObjects = new LinkedList<>();
try {
ObjectMapper objectMapper = new ObjectMapper();
ObjectReader objectReader = objectMapper.readerFor(MyPojo.class);
Iterator<MyPojo> iterator = objectReader.readValues(srcFile);
while (iterator.hasNext()) {
jsonObjects.add(iterator.next());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
// manipulation operations ...
return jsonObjects;
}
Write
public void writeNewMyPojos(File srcFile, List<MyPojo> newFileContents) {
String srcFileName = srcFile.getName();
int fileExtensionIndex = srcFileName.lastIndexOf('.');
String destFileExtension = srcFileName.substring(fileExtensionIndex);
String destFileName = srcFileName.substring(0, fileExtensionIndex) + "_updated" + destFileExtension;
File destFile = new File(srcFile.getParentFile(), destFileName);
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
objectMapper.writeValue(destFile, newFileContents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
As for the results:
Example Input
newFileContents = List.of(
new MyPojo("Test1", 1, 2),
new MyPojo("Test2", 1, 2),
new MyPojo("Test3", 1, 2)
);
Expected Output (roughly)
[
{
"comment" : "Test1",
"pos" : 1,
"type" : 2
},
{
"comment" : "Test2",
"pos" : 1,
"type" : 2
},
{
"comment" : "Test3",
"pos" : 1,
"type" : 2
}
]
Actual Output
[ {
"comment" : "Test1",
"pos" : 1,
"type" : 2
}, {
"comment" : "Test2",
"pos" : 1,
"type" : 2
}, {
"comment" : "Test3",
"pos" : 1,
"type" : 2
} ]
I’ve tried jackson 2.17, 2.16 and even 2.13 (as ChatGPT seems to use that version) to no avail.