To read a JSON file in Java, you can use the JSON-simple library, which is a simple and easy-to-use library for parsing and creating JSON.
Here is an example of how you can use the JSON-simple library to read a JSON file in Java:
rt refeo:lautturi.comimport java.io.FileReader; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class JSONReader { public static void main(String[] args) throws IOException, ParseException { JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(new FileReader("example.json")); String name = (String) json.get("name"); long age = (Long) json.get("age"); JSONArray hobbies = (JSONArray) json.get("hobbies"); System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Hobbies: " + hobbies); } }
In this example, the main
method creates a JSONParser
object and uses it to parse the JSON file using the parse
method. The method returns a JSONObject
, which represents the root object of the JSON file.
The JSONObject
is used to extract the values of the "name", "age", and "hobbies" fields using the get
method. The values are then printed to the console using the System.out.println
method.
This code will read the JSON file and print the values of the "name", "age", and "hobbies" fields to the console. You can modify the code to store the data in a data structure or perform other operations with it.
Keep in mind that this is just one way to read a JSON file in Java. You can use different techniques and libraries to achieve the same result, such as using the Gson
library or parsing the JSON file manually using the JSONObject
and JSONArray
classes.