ModelObjectArray
~ Array creation fix for createModelObjectArray()
package com.wrapper.spotify.objects;
import com.google.common.reflect.TypeToken;
-import com.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
+import com.google.gson.*;
+import java.lang.reflect.Array;
+import java.lang.reflect.Type;
import java.util.TimeZone;
public abstract class AbstractModelObject implements IModelObject {
@@ -22,8 +21,22 @@ public abstract class AbstractModelObject implements IModelObject {
}
public T[] createModelObjectArray(JsonArray jsonArray) {
- return new Gson().fromJson(jsonArray, new TypeToken<T>() {
- }.getType());
+ @SuppressWarnings("unchecked")
+ T[] array = (T[]) Array.newInstance(new TypeToken<T>(getClass()) {
+ }.getRawType(), jsonArray.size());
+
+ for (int i = 0; i < jsonArray.size(); i++) {
+ JsonElement jsonElement = jsonArray.get(i);
+
+ if (jsonElement instanceof JsonNull) {
+ array[i] = null;
+ } else {
+ JsonObject jsonObject = jsonElement.getAsJsonObject();
+ array[i] = createModelObject(jsonObject);
+ }
+ }
+
+ return array;
}
public T[] createModelObjectArray(String json) {
@@ -31,11 +44,22 @@ public abstract class AbstractModelObject implements IModelObject {
}
public <X> X[] createModelObjectArray(JsonArray jsonArray, TypeToken<X> typeToken) {
- return new Gson().fromJson(jsonArray, new TypeToken<X>() {
- }.getType());
+ @SuppressWarnings("unchecked")
+ X[] array = (X[]) Array.newInstance(typeToken.getRawType(), jsonArray.size());
+
+ for (int i = 0; i < jsonArray.size(); i++) {
+ JsonElement jsonElement = jsonArray.get(i);
+ JsonObject jsonObject = jsonElement.getAsJsonObject();
+ array[i] = (X) createModelObject(jsonObject);
+ }
+
+ return array;
}
public Paging<T> createModelObjectPaging(JsonObject jsonObject) {
+ Type type = new TypeToken<T>(getClass()) {
+ }.getType();
+
return new Paging.Builder<T>()
.setHref(jsonObject.get("href").getAsString())
.setItems(createModelObjectArray(jsonObject.getAsJsonArray("items")))
