【问题标题】:Storing JSON Response in an array将 JSON 响应存储在数组中
【发布时间】:2016-02-08 16:36:16
【问题描述】:

我正在尝试将 json 数组响应存储到数组列表中。 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&lt;T&gt;的解决方案,现在得到了这个错误:

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 错误。

【问题讨论】:

  • TypeToken>(){}.getType(); responseClass 在哪里定义?使用通配符或确切的类定义

标签: java arrays json list gson


【解决方案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 值进行硬编码。

【讨论】:

    【解决方案2】:

    给你的问题是这一行:

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

    【讨论】:

    【解决方案3】:

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

    或尝试阅读此内容 http://androidengineer.weebly.com/tutorials/json-to-gson-to-java-with-httpurlconnection-in-android @SerializedName(名字) 私有字符串名;

    @SerializedName("firstName")
    private String middleName;
    
    @SerializedName("lastName")
    private String lastName;
    
    @SerializedName("gender")
    private LocalDate dateOfBirth;
    

    结束等等……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多