Question

my json object starts with an object, then contains an array of the object I want { "myObjectArray":[ {....} , {....} , {....} ] }, I have made the model file for the object represented in {....} , how do I get this generic collection code to not assume my root element is an array without making a new nested object file

This is what I currently have,

 Type listType = new TypeToken<List<T>>() {
                }.getType();
 List<T> yourClassList = new Gson().fromJson(jsonArray, listType);

but this assumes that my json object is constructed like this [{....}, {....}, {....}] instead of the way I detailed above

Therefore, parsing returns a JsonSyntaxException

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Without creating a pointless model object that contains one variable "myObjectArray" which contains a List of myObject , how would I modify a GSON builder to accomodate?

(I am using android so I can't use a lot of the Oracle JVM reflection methods, including ParameterizedTypeImpl)

Was it helpful?

Solution

using

GsonBuilder builder = new GsonBuilder(); 
mGson = builder.enableComplexMapKeySerialization().create();
listType = new TypeToken<Map<String, List<T>>>() {}.getType();
parsedGSON = mGson.fromJson(reader, listType); 

is the answer

GSON creates a LinkedTreeMap object

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top