将JSON响应存储在数组

时间:2016-02-08 16:36:17

标签: java arrays json list gson

我正在尝试将json数组响应存储到arraylist中。以下是JSON响应的样子:

"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",
        }
    ]
}

这是Identity类:

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;
    }
}

基于我在here等其他SO帖子上发现的内容,我编写了这个函数来解析它:

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);
}

并且这样称呼它:

getResponseObjectAsArray(resourceResponse, "identityList", Identity.class)

resourceResponse是字符串格式的json响应。但是我的getResponseObjectAsArray方法出现语法错误:

Error:(39, 44) java: cannot find symbol
  symbol:   class responseClass

我正在尝试使用传递给方法的任何类来对列表进行参数化,因为它可能是许多其他类型的列表,而不仅仅是Identity。我在这做错了什么?

修改1:尝试了List<T>的解决方案并立即收到此错误:

Error:(41, 20) java: no suitable method found for fromJson(org.json.JSONArray,java.lang.reflect.Type)
    method com.google.gson.Gson.<T>fromJson(java.lang.String,java.lang.Class<T>) is not applicable
      (cannot infer type-variable(s) T
        (argument mismatch; org.json.JSONArray cannot be converted to java.lang.String))
    method com.google.gson.Gson.<T>fromJson(java.lang.String,java.lang.reflect.Type) is not applicable
      (cannot infer type-variable(s) T
        (argument mismatch; org.json.JSONArray cannot be converted to java.lang.String))
    method com.google.gson.Gson.<T>fromJson(java.io.Reader,java.lang.Class<T>) is not applicable
      (cannot infer type-variable(s) T
        (argument mismatch; org.json.JSONArray cannot be converted to java.io.Reader))
    method com.google.gson.Gson.<T>fromJson(java.io.Reader,java.lang.reflect.Type) is not applicable
      (cannot infer type-variable(s) T
        (argument mismatch; org.json.JSONArray cannot be converted to java.io.Reader))
    method com.google.gson.Gson.<T>fromJson(com.google.gson.stream.JsonReader,java.lang.reflect.Type) is not applicable
      (cannot infer type-variable(s) T
        (argument mismatch; org.json.JSONArray cannot be converted to com.google.gson.stream.JsonReader))
    method com.google.gson.Gson.<T>fromJson(com.google.gson.JsonElement,java.lang.Class<T>) is not applicable
      (cannot infer type-variable(s) T
        (argument mismatch; org.json.JSONArray cannot be converted to com.google.gson.JsonElement))
    method com.google.gson.Gson.<T>fromJson(com.google.gson.JsonElement,java.lang.reflect.Type) is not applicable
      (cannot infer type-variable(s) T
        (argument mismatch; org.json.JSONArray cannot be converted to com.google.gson.JsonElement))

编辑2:以下是另一种参数化列表对象的尝试:

public static <T> List<T> getResponseObjectAsArray(String resourceResponse, String jsonObject, Class<T> responseClass) {
    JSONArray jsonResponse = new JSONObject(resourceResponse).getJSONObject("identityList").getJSONArray(jsonObject);
    return gson.fromJson(jsonResponse.toString(), List<responseClass>);
}

我现在刚刚对identityList字符串进行了硬编码,但后来我将其作为用户输入。但是我仍然无法对fromJson调用内的列表进行参数化。我收到Expression expected错误。

3 个答案:

答案 0 :(得分:1)

感谢this post我想出了如何实现我想要的东西。这是现在的代码:

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());
}

还有一些问题需要解决,例如正确的错误处理,而不是对getJson值进行硬编码。

答案 1 :(得分:0)

给你问题的一行是这个:

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

因为responseClass是一个对象。 Java中的类型检查是静态的,因此它不接受类对象作为List的特化参数。您可以通过简单地将其更改为静态已知类型T来解决此问题:

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

修改

getResponseObjectAsArray应该返回一个T数组,而不是单个元素T.问题是由于类型擦除而获取泛型类数组的类。

@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);
    }
}

答案 2 :(得分:0)

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

或尝试阅读此内容 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;

结束......