I have three nested classes as the following:
public class A {
String s1;
String s2;
String s3;
String s4;
String s5;
String s6;
String s7;
String s8;
B b;
}
public class B{
private Map<String, C> ag = new HashMap<>();
}
public class C{
private Map<String, Boolean> ar = new HashMap<>();
}
Class A is sent as a GET method reply of type JSON to an Android app which consumes the service as shown bellow:
Gson gson = new GsonBuilder()
.enableComplexMapKeySerialization()
.setLenient()
.create();
Retrofit r = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
...
However, when running the Android app, I get the following error:
E/Rest GET Error: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line ? column ? B.ag.
Having in mind that If I remove class b field from class A, everything goes smoothly. It seems that gson is unable to deserialize a composed JSON file. So what to do?
Note: The JSON file is retrieved successfully from a Restful webservice using MOXy not Jackson. So there is no option to use @JsonDeserialize.
Below is the returned JSON file:
{"b":{"ag":{"entry":[{"key":"AS2","value":{"ar":{"entry":[{"key":"s1","value":false},{"key":"s2","value":false},{"key":"s3","value":false},{"key":"s4","value":false},{"key":"s5","value":false},{"key":"s6","value":true},{"key":"s7","value":false},{"key":"s8","value":false}]}}},{"key":"AS3","value":{"ar":{"entry":[{"key":"s1","value":false},{"key":"s2","value":true},{"key":"s3","value":true},{"key":"s4","value":false},{"key":"s5","value":false},{"key":"s6","value":false},{"key":"s7","value":false},{"key":"s8","value":true}]}}},{"key":"AS1","value":{"ar":{"entry":[{"key":"s1","value":false},{"key":"s2","value":true},{"key":"s3","value":true},{"key":"s4","value":false},{"key":"s5","value":false},{"key":"s6","value":false},{"key":"s7","value":false},{"key":"s8","value":false}]}}}]}},"s1":"string1","s2":"string2","s3":"string3","s4":"string4","s5":"string5","s6":"string6","s7":"string7","s8":"string8"}
From your class and error provided it seem that you are getting Array at B b; in Class A . We can say exact problem if you share jsonResponse.
----Updated---
Change your Class B
Class B{
private Ag ag;
}
class Ag {
List<Entry> entry;
}
class Entry{
String key;
Value value;
}
class Value{
Ar ar;
}
class Ar{
List<ArEntry> entry;
}
class ArEntry{
String key;
Boolean value;
}
This is how your classes for the jsonResponse you provided.
You can convert any json response to pojo here or you can add Android Studio plugin here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.