Skip to content

Instantly share code, notes, and snippets.

@benek
Created July 9, 2020 08:50
Show Gist options
  • Save benek/5931283bd27bd00cd0cbc5efaaed09bb to your computer and use it in GitHub Desktop.
Save benek/5931283bd27bd00cd0cbc5efaaed09bb to your computer and use it in GitHub Desktop.
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
/**
* Author: Javier Benek
* Just a simple test to sort the elements of a JSON document using TreeMap instead of LinkedHashMap
*/
public class SortJSON {
private final static Logger LOGGER = LoggerFactory.getLogger(SortJSON.class);
public void doSort(){
final JSONParser parser = new JSONParser();
final String jsonFileToLoad = "/path/to/file.json";
try {
final JSONObject json = (JSONObject) parser.parse(new FileReader(jsonFileToLoad));
LOGGER.debug("JSON loaded from file (original): {}", json.toJSONString());
final ObjectMapper mapper = new ObjectMapper();
final Map<String, Object> orderedMap = mapper.readValue(
json.toJSONString(), new TypeReference<Map<String, Object>>(){});
LOGGER.debug("JSON from LinkedHashMap: {}", new ObjectMapper().writeValueAsString(orderedMap));
final ObjectMapper mapperTreeMap = new ObjectMapper();
final SimpleModule module = new SimpleModule();
module.addAbstractTypeMapping(Map.class, TreeMap.class);
mapperTreeMap.registerModule(module);
final Map<String, Object> sortedMap = mapperTreeMap.readValue(
json.toJSONString(), new TypeReference<Map<String, Object>>(){});
LOGGER.debug("JSON from TreeMap: {}", mapperTreeMap.writeValueAsString(sortedMap));
} catch (FileNotFoundException e) {
LOGGER.debug("File was not found: -{}-", jsonFileToLoad);
} catch (IOException | ParseException e) {
LOGGER.debug("Exception while parsing or handling file: -{}-", jsonFileToLoad);
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment