Main Tutorials

Gson – How to parse JSON Arrays, an array of arrays

json array

In this article, we will show few JSON array examples and also how to use Gson to map it back to Java Object.

pom.xml

  <!-- Gson JSON -> Object -->
  <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.6</version>
  </dependency>

JSON basic.

  • [ ] = array
  • { } = object

1. JSON array of object.

1.1 Sample.

array1.json

[
  {
    "id": 1, "name": "a"
  },
  {
    "id": 2, "name": "b"
  }
]

1.2 Gson convert above JSON array into a List<Item>.

Item.java

package com.mkyong;

public class Item {

    private int id;
    private String name;

}
JsonArray1.java

package com.mkyong;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class JsonArray1 {

    public static void main(String[] args) throws IOException {

        JavaParseJsonArray main = new JavaParseJsonArray();

        Gson gson = new Gson();

        Type listType = new TypeToken<List<Item>>() {}.getType();

        List<Item> list = gson.fromJson(main.loadFileFromClasspath("array1.json"), listType);

        System.out.println(gson.toJson(list));

    }

    public String loadFileFromClasspath(String fileName) throws IOException {
        ClassLoader classLoader = getClass().getClassLoader();
        try (InputStream inputStream = classLoader.getResourceAsStream(fileName)) {
            // common-io
            return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        }
    }

}

P.S We use common-io to convert inputStream to String.

pom.xml

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

2. JSON array of {object with an array of object}.

2.1 Sample.

array2.json

[
  {
    "id": 1,
    "name": "a",
    "types":
    [
      {"id": 1,"name": "a1"},
      {"id": 2,"name": "a2"}
    ]
  },
  {
    "id": 2,
    "name": "b",
    "types":
    [
      {"id": 1,"name": "b1"},
      {"id": 2,"name": "b2"}
    ]
  }
]

2.2 Gson convert above JSON array into a List<Item> containing List<ItemType> types.

Item.java

package com.mkyong;

import java.util.List;

public class Item {

    private int id;
    private String name;
    private List<ItemType> types;

}
ItemType.java

package com.mkyong;

public class ItemType {

    private int id;
    private String name;

}

2.3 Same code, no need to change.


  Type listType = new TypeToken<List<Item>>() {}.getType();
  List<Item> list = gson.fromJson(main.loadFileFromClasspath("array2.json"), listType);

3. JSON array of {object with an array of an array of object}.

3.1 Sample.

array3.json

[
  {
    "id": 1,
    "name": "a",
    "types":
    [
      [
        {"id": 1,"name": "a1"},
        {"id": 2,"name": "a2"}
      ],
      [
        {"id": 3,"name": "a3"}
      ]
    ]
  },
  {
    "id": 2,
    "name": "b",
    "types":
    [
      [
        {"id": 1,"name": "b1"}
      ],
      [
        {"id": 2,"name": "b2"}
      ]
    ]
  }
]

3.2 Change the types to List<ItemType> types[];

Item.java

package com.mkyong;

import java.util.List;

public class Item {

    private int id;
    private String name;
    private List<ItemType> types[]; // change types -> types[]

}
ItemType.java

package com.mkyong;

public class ItemType {

    private int id;
    private String name;

}

3.3 Same code, no need to change.


  Type listType = new TypeToken<List<Item>>() {}.getType();
  List<Item> list = gson.fromJson(main.loadFileFromClasspath("array3.json"), listType);

3.4 See the debugging mode.

ideaj debug

4. JSON array of {object with an array of an array of String}.

4.1 This is a bit unusual JSON array sample.

array4.json

[
  {
    "id": 1,
    "name": "a",
    "types":
    [
      [
        "a1", 1
      ],
      [
        "a2", 2
      ]
    ]
  },
  {
    "id": 2,
    "name": "b",
    "types":
    [
      [
        "b1", 1
      ]
    ]
  }
]

4.2 Change the types to List<String> types[];

Item.java

package com.mkyong;

import java.util.List;

public class Item {

    private int id;
    private String name;
    private List<String> types[];

}

4.3 Same code, no need to change.


  Type listType = new TypeToken<List<Item>>() {}.getType();
  List<Item> list = gson.fromJson(main.loadFileFromClasspath("array4.json"), listType);

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
prakash
3 years ago

Whats the alternate to this line in scala
Type listType = new TypeToken<List<Item>>() {}.getType();

Juraj Hlevnjak
3 years ago

Thank youu!!

Belllaa Edward
3 years ago

Can you please help me get the data of Actor of selected movie ? How to use Gson here:

{
“status”: 1,
“message”: “Successful”,
“movie”: [
{
“movieId”: “1”,
“movieName”: “Enchanted”,
“movieStatus”: “1”,
“movieGenre”: “Comedy”,
“movieRating”: “2.5”,
“movieLanguage”: “English”,
“movieReleaseDate”: “2020-05-20”,
“movieDescription”: “Enchanted is a 2007 American live action/animated musical fantasy romantic comedy film, produced by Walt Disney Pictures, Sonnenfeld Productions and Josephson Entertainment. Written by Bill Kelly and directed by Kevin Lima, the film stars Amy Adams, Patrick Dempsey, James Marsden, Timothy Spall, Idina Menzel, Rachel Covey, and Susan Sarandon.”,
“movieImage”: “https://i.pinimg.com/originals/9e/46/25/9e4625b68e368f4134b5216051b6f4ab.jpg”,
“movieDirector”: “Kevin Lima”,
“movieDuration”: “01:47:00”,
“movieTrailerUrl”: “https://www.youtube.com/watch?v=moC6oA73wz0”,
“cast”: [
{
“castId”: “1”,
“movieId”: “1”,
“actor”: [
[],
{
“actorId”: “1”,
“actorName”: “Amy Adams”,
“actorRole”: “Female Main”,
“actorImage”: “https://static.toiimg.com/thumb/msid-55292369,width-800,height-600,resizemode-75,imgsize-47498,pt-32,y_pad-40/55292369.jpg”,
“castId”: “1”
},
{
“actorId”: “2”,
“actorName”: “Patrick Dempsey”,
“actorRole”: “Male Main”,
“actorImage”: “https://media.nbclosangeles.com/2019/09/092509-Patrick-Dempsey-Greys-Anatomy.jpg?resize=640%2C478”,
“castId”: “1”
},
{
“actorId”: “3”,
“actorName”: “James Marsden”,
“actorRole”: “Male Second”,
“actorImage”: “https://static.toiimg.com/thumb/msid-62860109,imgsize-46990,width-800,height-600,resizemode-75/62860109.jpg”,
“castId”: “1”
},
{
“actorId”: “4”,
“actorName”: “Susan Sarandon”,
“actorRole”: “Female Negative”,
“actorImage”: “https://magarticles.magzter.com/articles/5130/244918/5a097679bdc34/Susan-Sarandon-The-Ageless-Beauty.jpg”,
“castId”: “1”
},
{
“actorId”: “5”,
“actorName”: “Timothy Spall”,
“actorRole”: “Male Negative”,
“actorImage”: “https://www2.pictures.zimbio.com/gi/Timothy+Spall+Party+UK+Premiere+61st+BFI+London+Jq8evfClR1rl.jpg”,
“castId”: “1”
},
{
“actorId”: “6”,
“actorName”: “Idina Menzel”,
“actorRole”: “Female Second”,
“actorImage”: “https://img.huffingtonpost.com/asset/587421b21b00008d016e67f5.jpeg?cache=ozw4wactrx&ops=scalefit_630_noupscale”,
“castId”: “1”
}
]
}
]
}
]
}