Richard February 2016

Storing JSON Response in an array

I am trying to store a json array response into an arraylist. Here is what the JSON response looks like:

"identityList":{
    "identity":[
        {
            "firstName":"MICHAEL",
            "lastName":"JAMESON",
            "gender":"MALE",
            "dateOfBirth":"1961-05-18T00:00:00.000+0000",
        },
        {
            "firstName":"KELLY",
            "lastName":"JAMESON",
            "gender":"FEMALE",
            "dateOfBirth":"1951-04-01T00:00:43.000+0000",
        }
    ]
}

Here's the Identity class:

public class Identity {
    /** The first name. */
    private String firstName;

    /** the middleName. */
    private String middleName;

    /** the lastName. */
    private String lastName;

    /** the dateOfBirth. */
    private LocalDate dateOfBirth;

    public Identity(String firstName, String middleName, String lastName, LocalDate dateOfBirth) {
        super();
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;
        this.dateOfBirth = dateOfBirth;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getMiddleName() {
        return middleName;
    }

    public String getLastName() {
        return lastName;
    }

    public LocalDate getDateOfBirth() {
        return dateOfBirth;
    }
}

Based on what I've found on other SO posts like here I wrote this function to parse it:

public static <T> T getResponseObjectAsArray(String resourceResponse, String jsonObject, final Class<T> responseClass) {
    Type listType = new TypeToken<List<responseClass>>(){}.getType();
    JSONArray jsonResponse = new JSONObject(resourceResponse).getJSONArray(jsonObject);
    return gson.fromJson(jsonResponse, listType);
}

Answers


Andrew Williamson February 2016

The line giving you the issue is this one:

Type listType = new TypeToken<List<responseClass>>(){}.getType();

Since responseClass is an object. Type checking in Java is a static thing, so it does not accept a class object as a specialization parameter for List. You could fix this by simply changing it to the statically known type T:

Type listType = new TypeToken<List<T>>(){}.getType();

Edit

getResponseObjectAsArray should return an array of T, not a single element T. The problem is in getting the class of an array of generic types, due to type erasure.

@SuppressWarnings("unchecked")
public static <T> T[] getArray(String json, String field, final Class<T> clazz) {
    JSONArray array = new JSONObject(json).getJSONArray(field);
    try {
        Class<T[]> arrayClass = (Class<T[]>) Class.forName("[L" + clazz.getName() + ";");
        return gson.fromJson(array, arrayClass);
    } catch(ClassNotFoundException e) {
        // If T.class exists, then T[].class should also exist, so this should never be reached
        throw new RuntimeException(e);
    }
}


Trunks ssj February 2016

String jsonResultString = sb.toString(); ArrayList crawlerList = gson.fromJson(jsonResultString, new TypeToken>() {}.getType());

or try read this http://androidengineer.weebly.com/tutorials/json-to-gson-to-java-with-httpurlconnection-in-android @SerializedName(firstName) private String firstName;

@SerializedName("firstName")
private String middleName;

@SerializedName("lastName")
private String lastName;

@SerializedName("gender")
private LocalDate dateOfBirth;

end ect....


Richard February 2016

Thanks to this post I figured out how to implement what I want. Here's the code now:

public static <T> List<T> getResponseObjectAsArray(String resourceResponse, String jsonObject, Class<T> responseClass) {
    List<T> list = new ArrayList<T>();
    try {
        list.add(responseClass.getConstructor().newInstance());
    } catch(Exception e) {
        throw new RuntimeException(e);
    }
    JSONArray jsonResponse = new JSONObject(resourceResponse).getJSONObject("identityList").getJSONArray(jsonObject);
    return gson.fromJson(jsonResponse.toString(), list.getClass());
}

There's still stuff to fix like proper error handling and not hard coding the getJson value.

Post Status

Asked in February 2016
Viewed 2,795 times
Voted 6
Answered 3 times

Search




Leave an answer