如何抓取JSON数组并使用gson解析每个json对象? (改型)

时间:2021-11-19 13:41:28

I am returning an array of results with my json Objects, and I am trying to use my customObjectResponse class to pull out each of the fields within each of the objects... the problem it is expecting an object so how do I edit my class to allow it to take in an array of object to be able to then call the fields of each object... I am confused as to what needs to be added:

我正在使用我的json对象返回一个结果数组,我正在尝试使用我的customObjectResponse类来拉出每个对象中的每个字段...它期望一个对象的问题所以我如何编辑我的类允许它接受一个对象数组,然后可以调用每个对象的字段...我很困惑,需要添加什么:

Here is a response example of what is being passed to be used:

以下是要传递的内容的响应示例:

[ { itemId: 'dfsdfsdf343434',
       name: 'tests',
       picture: '6976-7jv8h5.jpg',
       description: 'testy.',
       dateUpdated: 1395101819,
       } ]

Here is my response Object Class:

这是我的响应对象类:

public class ObjResponse{
    private String itemId;
    private String name;
    private String picture;

    private String description;

    private String location;
    private int dateUpdated;

    private String msg;




    //gridview constructor
    public ObjResponse(String picture) {
        this.picture = picture;
    }

    //public constructor
    public ObjResponse() {

    }

    public String getItemId() {
        return itemId;
    }

    public void setItemId(String itemId) {
        this.itemId = itemId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPicture() {
        return picture;
    }

    public void setPicture(String picture) {
        this.picture = picture;
    }


    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }


    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }



    public int getDateUpdated() {
        return dateUpdated;
    }

    public void setDateUpdated(int dateUpdated) {
        this.dateUpdated = dateUpdated;
    }




    public String getMsg() {
        return msg;
    }

}

what I am trying, but is not working, even if I separate the classes into their own files:

我正在尝试,但不工作,即使我将类分成他们自己的文件:

Data passed in:
items: [{obj1: "A", obj2: ["c", "d"]}, {etc...}]


public class Response {

        public class List<Custom> {
                private List<Custom> items;
        }

        public class Custom {
                private String obj1;
                private List<Obj2> obj2;
        }

        public Class Obj2 {
                private String letters;
        }
}

4 个解决方案

#1


34  

I ended up just calling in the callback a list of the customObject and it did the job...

我最后只是在回调中调用了一个customObject列表,它完成了这项工作......

new Callback<List<ObjResponse>>() {

#2


10  

I originally had trouble getting an idea of how the OP solved his problem but, after days of debugging I have finally figured out how to solve this issue.

我原本无法了解OP如何解决他的问题,但经过几天的调试后我终于想出了如何解决这个问题。

So you essentially have data in the format like so (JSON Array of JSON Objects):

所以你基本上有这样的格式的数据(JSON数组的JSON对象):

[
    {
      ...
    }
] 

Your class that models the data and contains the getter and setter methods are nothing more than your typical POJO.

您为数据建模并包含getter和setter方法的类只不过是典型的POJO。

public class Person implements Serializable {
    @SerializedName("Exact format of your json field name goes here")
    private String firstName;

    // Getters and Setters....
}

In your interface that contains your RESTful annotations you want to convert your call from:

在包含RESTful注释的界面中,您要转换来自的呼叫:

Before:

之前:

public interface APInterface {
    @GET("SOME URL TO YOUR JSON ARRAY")
    Call<Person>(...)
}

After:

后:

public interface APInterface {
    @GET("SOME URL TO YOUR JSON ARRAY")
    Call<List<Person>>(...)
}

In your android activity you want to convert all calls in the form of Call<Person> to Call<List<Person>>

在您的Android活动中,您希望以Call 的形式将所有调用转换为Call >

Finally when making the initial asynchronous request call, you will want to convert your callbacks like so.

最后,在进行初始异步请求调用时,您需要像这样转换回调。

call.enqueue(new Callback<List<Person>>() {
    @Override
    public void onResponse(Call<List<Person>> call, Response<List<Person>> response) {

        if(response.isSuccessful()){
            List<Person> person = response.body();

           // Can iterate through list and grab Getters from POJO
           for(Person p: person){...}


        } else {
            // Error response...
        }

    }

    @Override
    public void onFailure(Call<List<Person>> call, Throwable t) {...}
});

Hope this helps others whom are lost from the accepted answer above.

希望这可以帮助那些因上述接受的答案而迷失的人。

#3


4  

This can also work by just passing an array of response objects. So if this is your response object:

这也可以通过传递响应对象数组来工作。所以如果这是你的响应对象:

public class CustomUserResponse {
    public String firstName;
    public String lastName;
    ...
}

You can use related syntax, depending on how you use the callbacks. Such as:

您可以使用相关语法,具体取决于您使用回调的方式。如:

new Callback<CustomUserResponse[]>(){
    @Override
    public void success(CustomUserResponse[] customUserResponses, Response rawResponse) {

    }

    @Override
    public void failure(RetrofitError error) {

    }
};

OR

要么

public class GetUserCommand implements Callback<CustomUserResponse[]> { ...

Put simply, in every place where you normally replace T with a response class, replace it with an array, instead as in CustomUserResponse[].

简而言之,在您通常用响应类替换T的每个地方,将其替换为数组,而不是像CustomUserResponse []中那样。


NOTE: to avoid confusing errors, be sure to also use an array in the Retrofit interface definition:

注意:为避免混淆错误,请务必在Retrofit接口定义中使用数组:

@POST ( "/users" )
public void listUsers(@Body GetUsersRequest request, Callback<CustomUserResponse[]> callback);

#4


2  

You could try something like this

你可以尝试这样的事情

JSONObject jsonObject = new JSONObject(<your JSON string result>);
JSONArray jsonArray = jsonObject.getJSONArray();

//use GSON to parse
if (jsonArray != null) {
   Gson gson = new Gson();
   ObjResponse[] objResponse = gson.fromJson(jsonArray.toString(), ObjResponse[].class);
   List<ObjResponse> objResponseList = Arrays.asList(objResponse);
}

This should definitely work.

这绝对有用。

#1


34  

I ended up just calling in the callback a list of the customObject and it did the job...

我最后只是在回调中调用了一个customObject列表,它完成了这项工作......

new Callback<List<ObjResponse>>() {

#2


10  

I originally had trouble getting an idea of how the OP solved his problem but, after days of debugging I have finally figured out how to solve this issue.

我原本无法了解OP如何解决他的问题,但经过几天的调试后我终于想出了如何解决这个问题。

So you essentially have data in the format like so (JSON Array of JSON Objects):

所以你基本上有这样的格式的数据(JSON数组的JSON对象):

[
    {
      ...
    }
] 

Your class that models the data and contains the getter and setter methods are nothing more than your typical POJO.

您为数据建模并包含getter和setter方法的类只不过是典型的POJO。

public class Person implements Serializable {
    @SerializedName("Exact format of your json field name goes here")
    private String firstName;

    // Getters and Setters....
}

In your interface that contains your RESTful annotations you want to convert your call from:

在包含RESTful注释的界面中,您要转换来自的呼叫:

Before:

之前:

public interface APInterface {
    @GET("SOME URL TO YOUR JSON ARRAY")
    Call<Person>(...)
}

After:

后:

public interface APInterface {
    @GET("SOME URL TO YOUR JSON ARRAY")
    Call<List<Person>>(...)
}

In your android activity you want to convert all calls in the form of Call<Person> to Call<List<Person>>

在您的Android活动中,您希望以Call 的形式将所有调用转换为Call >

Finally when making the initial asynchronous request call, you will want to convert your callbacks like so.

最后,在进行初始异步请求调用时,您需要像这样转换回调。

call.enqueue(new Callback<List<Person>>() {
    @Override
    public void onResponse(Call<List<Person>> call, Response<List<Person>> response) {

        if(response.isSuccessful()){
            List<Person> person = response.body();

           // Can iterate through list and grab Getters from POJO
           for(Person p: person){...}


        } else {
            // Error response...
        }

    }

    @Override
    public void onFailure(Call<List<Person>> call, Throwable t) {...}
});

Hope this helps others whom are lost from the accepted answer above.

希望这可以帮助那些因上述接受的答案而迷失的人。

#3


4  

This can also work by just passing an array of response objects. So if this is your response object:

这也可以通过传递响应对象数组来工作。所以如果这是你的响应对象:

public class CustomUserResponse {
    public String firstName;
    public String lastName;
    ...
}

You can use related syntax, depending on how you use the callbacks. Such as:

您可以使用相关语法,具体取决于您使用回调的方式。如:

new Callback<CustomUserResponse[]>(){
    @Override
    public void success(CustomUserResponse[] customUserResponses, Response rawResponse) {

    }

    @Override
    public void failure(RetrofitError error) {

    }
};

OR

要么

public class GetUserCommand implements Callback<CustomUserResponse[]> { ...

Put simply, in every place where you normally replace T with a response class, replace it with an array, instead as in CustomUserResponse[].

简而言之,在您通常用响应类替换T的每个地方,将其替换为数组,而不是像CustomUserResponse []中那样。


NOTE: to avoid confusing errors, be sure to also use an array in the Retrofit interface definition:

注意:为避免混淆错误,请务必在Retrofit接口定义中使用数组:

@POST ( "/users" )
public void listUsers(@Body GetUsersRequest request, Callback<CustomUserResponse[]> callback);

#4


2  

You could try something like this

你可以尝试这样的事情

JSONObject jsonObject = new JSONObject(<your JSON string result>);
JSONArray jsonArray = jsonObject.getJSONArray();

//use GSON to parse
if (jsonArray != null) {
   Gson gson = new Gson();
   ObjResponse[] objResponse = gson.fromJson(jsonArray.toString(), ObjResponse[].class);
   List<ObjResponse> objResponseList = Arrays.asList(objResponse);
}

This should definitely work.

这绝对有用。