简体   繁体   English

将JSON响应存储在数组中

[英]Storing JSON Response in an array

I am trying to store a json array response into an arraylist. 我正在尝试将json数组响应存储到arraylist中。 Here is what the JSON response looks like: 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",
        }
    ]
}

Here's the Identity class: 这是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;
    }
}

Based on what I've found on other SO posts like here I wrote this function to parse it: 根据我在其他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);
}

And calling it like this: 并这样称呼它:

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

With resourceResponse being the json response in a string format. 其中resourceResponse是字符串格式的json响应。 But I get a syntax error with the getResponseObjectAsArray method that says: 但是我在getResponseObjectAsArray方法中收到语法错误,内容为:

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

I'm trying to parametrize the list with whatever class passed into the method because it could be a list of many other types and not just Identity . 我试图用传递给该方法的任何类对列表进行参数化,因为它可能是许多其他类型的列表,而不仅仅是Identity What am i doing wrong here? 我在这里做错了什么?

Edit 1: Tried the solution of List<T> and got this error now: 编辑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))

Edit 2: Here's another attempt at parametrizing a list object: 编辑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>);
}

I just hardcoded the identityList string for now but later I'll make it as user input. 我现在只是对identityList字符串进行硬编码,但稍后将其作为用户输入。 But I'm still unable to parametrize the list inside of the fromJson call. 但是我仍然无法参数化fromJson调用中的列表。 I'm getting an Expression expected error. 我收到Expression expected错误。

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. 还有一些东西需要修复,例如正确的错误处理,而不是硬编码getJson值。

The line giving you the issue is this one: 给您问题的那一行是这个:

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

Since responseClass is an object. 由于responseClass是一个对象。 Type checking in Java is a static thing, so it does not accept a class object as a specialization parameter for List. Java中的类型检查是静态的,因此它不接受类对象作为List的特殊化参数。 You could fix this by simply changing it to the statically known type T: 您可以通过将其更改为静态已知的类型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. 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);
    }
}

String jsonResultString = sb.toString(); 字符串jsonResultString = sb.toString(); ArrayList crawlerList = gson.fromJson(jsonResultString, new TypeToken>() {}.getType()); 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; 或尝试阅读此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.... 结束...。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM