coding made simple with some delicious cake

Read JSON file and convert to List in Java

In this post we will provide an example of how to read a JSON file and convert its contents to a list in Java. The JSON file will consist of an array of objects, the file will be read and each array object will be converted to a Java object.

Setup:

You will need to include the following dependancy in your maven project.

1

2

3

4

5

<dependency>

<groupId>com.google.code.gson</groupId>

<artifactId>gson</artifactId>

<version>2.3.1</version>

</dependency>

Read JSON file and convert to List example:

Assume we have the following JSON file called jsonFile.txt :

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

[{

"name": "Mat",

"age": 22,

"address": {

"line1": "peter road",

"postcode": "w1"

}

},

{

"name": "John",

"age": 35,

"address": {

"line1": "boston road",

"postcode": "w4 "

}

},

{

"name": "Peter",

"age": 2,

"address": {

"line1": "eve road",

"postcode": "w3"

}

},

{

"name": "George",

"age": 25,

"address": {

"line1": "taylor road",

"postcode": "w9"

}

}]

And we have the following Java objects defined (User and Address).

User object

Java

1

2

3

4

5

6

7

publicclassUser{

privateStringname;

privateintage;

privateAddress address;

//getters and constructors

}

Address object

Java

1

2

3

4

5

6

publicclassAddress{

privateStringline1;

privateStringpostcode;

//getters and constructors

}

The example below, is using GSON to read the file named jsonFile.txt and converting it to a List of User objects by using a TypedToken. The TypedToken tell GSON how you want the JSON translated, in our case a list of user objects.