Posted In: GSON, JSON

Gson – Deserialize json array to list generic type

Converting JSON array to ArrayList<generic> can be achieved using com.google.gson.reflect.TypeToken

package com.javausecase.gson;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class JsonArrayToList {
	@Test
	public void main() throws Exception {
		System.out.println("Start");
		String json = "[{\"name\":\"abc\", \"course\":\"java\"},"
				+ "{\"name\":\"abc2\", \"course\":\"java2\"}]";
		Type listType = new TypeToken<ArrayList<Student3>>() {
		}.getType();
		List<Student3> students = new Gson().fromJson(json, listType);
		System.out.println(students);
	}
}

class Student3 {
	String name;
	String course;

	@Override
	public String toString() {
		return "Student [name=" + name + ", course=" + course + "]";
	}
}

Tags:

by , on February 22nd, 2018