Posted In: GSON, JSON

GSON – Resolving Expected BEGIN_OBJECT but was BEGIN_ARRAY exception

Code will throw following error

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 13 path $.student
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)

package com.javausecase.gson;

import org.junit.Test;

import com.google.gson.Gson;

public class BeginObjectError {
	@Test
	public void main() throws Exception {
		System.out.println("Start");
		String json = "{\"student\":[{\"name\":\"abc\", \"course\":\"java\"}]}";
		Gson gson = new Gson();
		University university = gson.fromJson(json, University.class);
		System.out.println("End");
	}
}

class University {
	Student student;
}

class Student {
	String name;
	String course;
}

To resolve either POJO or input JSON needs to be corrected

package com.javausecase.gson;

import java.util.List;

import org.junit.Test;

import com.google.gson.Gson;

public class BeginObjectError {
	@Test
	public void main() throws Exception {
		System.out.println("Start");
		String json = "{\"students\":[{\"name\":\"abc\", \"course\":\"java\"}]}";
		Gson gson = new Gson();
		University university = gson.fromJson(json, University.class);
		System.out.println(university);
	}
}

class University {
	List<Student> students;

	@Override
	public String toString() {
		return "University [students=" + students + "]";
	}
}

class Student {
	String name;
	String course;

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

by , on February 22nd, 2018

  • Categories