With this code, I am trying read all of the data from a JSON file, parse it with Jackson, remove unwanted fields, and put the remaining fields into a new file.
So far, my code works, except ObjectMapper.readTree only reads the first object in the JSON file. I know I need to loop through each object in the file, but I don't know how to iterate through the tree.
Thank you in advance,
David Riley
public class App {
public static void main(String[] args) throws IOException {
File file = new File("exampleFile.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
JsonNode root = mapper.readTree(file);
JsonCleaner jsonCleaner = new JsonCleaner(root, (node) -> node != null);// isNumber());
JsonNode result = jsonCleaner.removeAll();
File cardFile = new File("masterCardList.json");
FileWriter fileWriter;
try {
cardFile.createNewFile();
fileWriter = new FileWriter(cardFile, true);
fileWriter.write(result.toString() + ",");
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class JsonCleaner {
private final JsonNode root;
private final Predicate<JsonNode> toRemoveCondition;
JsonCleaner(JsonNode node, Predicate<JsonNode> toRemoveCondition) {
this.root = Objects.requireNonNull(node);
this.toRemoveCondition = Objects.requireNonNull(toRemoveCondition);
}
public JsonNode removeAll() {
process(root);
return root;
}
private void process(JsonNode node) {
if (node.isObject()) {
ObjectNode object = (ObjectNode) node;
Iterator<Map.Entry<String, JsonNode>> fields = object.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
JsonNode valueToCheck = field.getValue();
// System.out.println(field.getKey());
if (field.getKey() == "artist" || field.getKey() == "colors" ||
field.getKey() == "multiverseId" || field.getKey() == "scryfallId" ||
field.getKey() == "manaCost" || field.getKey() == "name" || field.getKey() == "rarity" ||
field.getKey() == "type" || (field.getKey() == "identifiers")) {
process(valueToCheck);
} else {
fields.remove();
}
}
} else if (node.isArray()) {
ArrayNode array = (ArrayNode) node;
array.elements().forEachRemaining(this::process);
}
}
}