A T A T - 2 months ago 20
Java Question

gson JsonSyntaxException: Expected BEGIN_OBJECT but was NUMBER

Main.java



import java.util.*;
import java.lang.*;
import java.io.*;
import com.google.gson.Gson;

class Main {
public static void main (String[] args) throws java.lang.Exception {
final Gson gson = new Gson();
final ErrorResponse errorResponse = gson.fromJson(
"{\"error\": \"FOO\", \"error_message\": \"BAR\"}",
ErrorResponse.class);
System.out.println("errorResponse = " + errorResponse);
}
}


ErrorResponse.java



import java.util.Locale;


public class ErrorResponse {
private String mError;
private String mErrorMessage;

private ErrorResponse() {}

public ErrorResponse(final String error, final String errorMessage) {
mError = error;
mErrorMessage = errorMessage;
}

@Override
public final String toString() {
return String.format(Locale.getDefault(), "%s: %s",
mError, mErrorMessage);
}
}



"com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 4 path $"

Answer

For field matching you will have to use the @Serialized annotation. The field members on your bean are mError and mErrorMessage and on your json are error and error_message. I have used the serialized annotation here

This prints errorResponse = FOO: BAR

import java.util.Locale;

import com.google.gson.annotations.SerializedName;

public class ErrorResponse {
    @SerializedName("error")
    private String mError;
    @SerializedName("error_message")
    private String mErrorMessage;

    private ErrorResponse() {
    }

    public ErrorResponse(final String error, final String errorMessage) {
        mError = error;
        mErrorMessage = errorMessage;
    }

    @Override
    public final String toString() {
        return String.format(Locale.getDefault(), "%s: %s", mError, mErrorMessage);
    }
}