Created
September 7, 2023 00:34
-
-
Save mkasberg/da0a1030e39cfa57cdf4c0382ad3eeaf to your computer and use it in GitHub Desktop.
Boilerplate to parse JSON in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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