How to read json file into java with simple JSON library
How to read json file into java with simple JSON library
The whole file is an array and there are objects and other arrays (e.g. cars) in the whole array of the file.
As you say, the outermost layer of your JSON blob is an array. Therefore, your parser will return a JSONArray
. You can then get JSONObject
s from the array …
JSONArray a = (JSONArray) parser.parse(new FileReader(c:\exer4-courses.json));
for (Object o : a)
{
JSONObject person = (JSONObject) o;
String name = (String) person.get(name);
System.out.println(name);
String city = (String) person.get(city);
System.out.println(city);
String job = (String) person.get(job);
System.out.println(job);
JSONArray cars = (JSONArray) person.get(cars);
for (Object c : cars)
{
System.out.println(c+);
}
}
For reference, see Example 1 on the json-simple decoding example page.
You can use jackson library and simply use these 3 lines to convert your json file to Java Object.
ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream(/test.json);
testObj = mapper.readValue(is, Test.class);
How to read json file into java with simple JSON library
Add Jackson databind:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0.pr2</version>
</dependency>
Create DTO class with related fields and read JSON file:
ObjectMapper objectMapper = new ObjectMapper();
ExampleClass example = objectMapper.readValue(new File(example.json), ExampleClass.class);