I am trying to convert response string into a java object (of Temp Class) for further manipulating but I get below error:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 3 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
at com.google.gson.Gson.fromJson(Gson.java:963)
at com.google.gson.Gson.from
import com.google.gson.*;
class Temp {
String name = "";
int age = 0;
String city = "";
}
class Scratch {
public static void main(String[] args) {
String response = " '{"name":"John", "age":30, "city":"New York"}' ";
//convert response to Temp object
Gson g = new Gson();
Temp t = g.fromJson(response, Temp.class);
System.out.println(t.age);
}
}
response is already a JSON String. Why can’t I convert it to Temp Class object?
2
Answers
Your response String starts with a ‘ and it shouldn’t be. Also I note that there are unnecessary spaces in that same String.
Your response String should be as follows,
There is error in the JSON Response itself. The response string includes extra spaces and single quotes, which is not the correct JSON format.
Consider the following corrected code.