Search code examples
javaandroidjsonjsonserializerjson-serializable

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1


I am trying to serialize the bellow JSON data in java

  [{
    "clear": "0",
    "default": ["123","234"],
    "mandatory": "1",
    "visible": "1"
}]

my serializer Class looks like bellow,

public class HandleConfig{
@SerializedName("visible")
private  int visible;
@SerializedName("clear")
private  int clear;
@SerializedName("mandatory")
private int mandatory;
@SerializedName("default")
private JSONArray def;

// getter and setter methods here...

}

//call to the serializer

Gson gson1 = new Gson();
Type collectionType1 = new TypeToken<List<HandleConfig>>(){}.getType();
List<HandleConfig> handleConfigurations = gson1.fromJson(object.toString(), collectionType1);

// the Error

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 267 path $[0].default

I have referred various stack Overflow answers.. and come to know the reason behind this is serializer is expecting the "default" to be the bellow format

 "default":[{ "id":123},{"id":124}]

but now my question is how to serialize "defalut":["123","1234"] to JSON Array without producing any errors,

thanks in advance.. :)


Solution

  • Please use this for that parsing :

    List<String> def instead of JSONArray def