How to read json file into java with simple JSON library
To read a JSON file into Java using the Simple JSON library, you can use the JSONObject
class and the JSONArray
class.
Here's an example of how you can read a JSON file into a Java object using the Simple JSON library:
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
// Create a JSON parser
JSONParser parser = new JSONParser();
try {
// Read the JSON file and parse it
Object obj = parser.parse(new FileReader("data.json"));
// Convert the parsed object to a JSONObject
JSONObject jsonObject = (JSONObject) obj;
// Get the value of the "name" field
String name = (String) jsonObject.get("name");
System.out.println(name); // prints "John Smith"
// Get the value of the "age" field
long age = (long) jsonObject.get("age");
System.out.println(age); // prints 30
// Get the value of the "skills" field
JSONArray skills = (JSONArray) jsonObject.get("skills");
for (Object skill : skills) {
System.out.println(skill); // prints "Java" and "Python"
}
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}
In this example, the JSONParser
is used to parse the JSON file and create a Java object. The object is then cast to a JSONObject
and the values of the various fields are extracted using the get()
method.
I hope this helps! Let me know if you have any questions.