Skip to content

Instantly share code, notes, and snippets.

@mkasberg
Created September 7, 2023 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkasberg/da0a1030e39cfa57cdf4c0382ad3eeaf to your computer and use it in GitHub Desktop.
Save mkasberg/da0a1030e39cfa57cdf4c0382ad3eeaf to your computer and use it in GitHub Desktop.
Boilerplate to parse JSON in Java
/**
* Download the latest json-java.jar from https://github.com/stleary/JSON-java#readme
* Place it in the same folder as this file
*
* Compile (Windows): javac -cp .;json-java.jar ParseJson.java
* Compile (Unix): javac -cp .:json-java.jar ParseJson.java
*
* Run (Windows): java -cp .;json-java.jar ParseJson FILENAME.json
* Run (Unix): java -cp .:json-java.jar ParseJson FILENAME.json
*/
import org.json.JSONObject;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
class ParseJson {
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.out.println("Usage: java -cp .:json-java.jar ParseJson FILENAME.json");
System.exit(1);
}
String fileName = args[0];
String fileContents = new String(Files.readAllBytes(Paths.get(fileName)));
JSONObject data = new JSONObject(fileContents);
System.out.println(data.toString(2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment