I’m working on a web service that is written in Java and I have to get the response from a JSON format. Below is the JSON. How can I get the values properly so I can used them?
{
"message": "string",
"validationErrors": [
{
"code": "string",
"message": "string"
}
],
"exceptionMessages": [
{
"code": "string",
"message": "string"
}
],
"trailId": "string",
"isSuccessful": true
}
This is what I’m trying, but I’m getting an error.
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
Type listErrors = new TypeToken<List<Response>>() {}.getType();
List<Response> list = gson.fromJson(response.toString(), listErrors);
This is the error I am getting when testing.
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
Response.java
import java.util.List;
public class Response{
public Response() {
super();
}
private String message;
private List<ValidationErrors> errors;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setErrors(List<ValidationErrors> errors) {
this.errors = errors;
}
public List<ValidationErrors> getErrors() {
return errors;
}
}
ValidationErrors.java
public class ValidationErrors {
public ValidationErrors() {
super();
}
private String code;
private String message;
public void setCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
2
Answers
As my understanding is correct, you only get one object, not a List:
To map the object correctl, you have also to rename the properties, so they fit to the key names in the json structure:
or add the
SerializedName
annotation to it:and add the property for the missing keys
exceptionMessages
,trailId
andisSuccessful
.You are getting this error as your json response is object and you are trying to parse as it is an array but it not..
that why it is showing like
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
your should replace code as mentioned below
From
To