无法使用GSON识别我的json的特定数组。并将它们添加到列表中

时间:2018-02-07 13:54:53

标签: android json gson jsonparser

主要活动代码片段...我已经尝试过responce.getObject但它没有用......

strtotime()

Myjson文件

 $args = array(
    'post_type'      => 'fw-event',
    'posts_per_page' => - 1,
    'meta_key'       => 'my_date',
    'order'          => 'DESC',
    'orderby'        => 'meta_value_num',
);

如何识别对象“数据”并访问所有数组。

3 个答案:

答案 0 :(得分:0)

您需要解析整个JSON响应,而不仅仅是"数据"属性。用于解析它的GSON文件可能如下所示:

public class MyJsonResponse {
    @SerializedName("code")
    private int code;
    @SerializedName("message")
    private String message;
    @SerializedName("data")
    private List<Person> data;
}

然后,您可以从已解析的响应中获取数据字段。

答案 1 :(得分:0)

您可以使用this link将json响应转换为POJO类。 对于您当前的回复,它就像是,它还实现了以下Parcelable代码:

JsonResponse.java

public class JsonResponse implements Parcelable
{

@SerializedName("code")
@Expose
private Integer code;
@SerializedName("message")
@Expose
private String message;
@SerializedName("data")
@Expose
private List<Datum> data = null;
public final static Parcelable.Creator<JsonResponse> CREATOR = new Creator<JsonResponse>() {


@SuppressWarnings({
"unchecked"
})
public JsonResponse createFromParcel(Parcel in) {
return new JsonResponse(in);
}

public JsonResponse[] newArray(int size) {
return (new JsonResponse[size]);
}

}
;

protected JsonResponse(Parcel in) {
this.code = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.message = ((String) in.readValue((String.class.getClassLoader())));
in.readList(this.data, (com.heyoe_chat.model.Datum.class.getClassLoader()));
}

public JsonResponse() {
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public List<Datum> getData() {
return data;
}

public void setData(List<Datum> data) {
this.data = data;
}

public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(code);
dest.writeValue(message);
dest.writeList(data);
}

public int describeContents() {
return 0;
}

}

Datum.java表示数组中的对象。

public class Datum implements Parcelable
{

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("skills")
@Expose
private String skills;
@SerializedName("image")
@Expose
private String image;
public final static Parcelable.Creator<Datum> CREATOR = new Creator<Datum>() {


@SuppressWarnings({
"unchecked"
})
public Datum createFromParcel(Parcel in) {
return new Datum(in);
}

public Datum[] newArray(int size) {
return (new Datum[size]);
}

}
;

protected Datum(Parcel in) {
this.id = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.name = ((String) in.readValue((String.class.getClassLoader())));
this.skills = ((String) in.readValue((String.class.getClassLoader())));
this.image = ((String) in.readValue((String.class.getClassLoader())));
}

public Datum() {
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

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

public String getSkills() {
return skills;
}

public void setSkills(String skills) {
this.skills = skills;
}

public String getImage() {
return image;
}

public void setImage(String image) {
this.image = image;
}

public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(id);
dest.writeValue(name);
dest.writeValue(skills);
dest.writeValue(image);
}

public int describeContents() {
return 0;
}

}

答案 2 :(得分:0)

首先,在这种情况下你不能使用 JsonArrayRequest 。这是因为您的 Myjson文件在根目录下没有数组,而是一个对象。您应该使用 JsonObjectRequest

所以这就是你的代码的样子:

JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
            URL,
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (response == null) {
                        Toast.makeText(getApplicationContext(), "Couldn't fetch the menu! Pleas try again.", Toast.LENGTH_LONG).show();
                        return;
                    }
                    Person persons = new Gson().fromJson(response.toString(), new TypeToken<Person>() {
                    }.getType());

                    // adding persons to cart list
                    cartList.clear();
                    cartList.add(persons);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("error", error.toString());
                }
    });

记得改变

 List<Person> persons = new Gson().fromJson(response.toString(), new TypeToken<List<Person>>() {
                    }.getType());

Person persons = new Gson().fromJson(response.toString(), new TypeToken<Person>() {
                }.getType());

这是因为与上述相同的原因:您正在获取 json对象而不是 json数组

现在, Gson 的工作方式是它需要一个类来“映射”收到的 Gson 。因此,您必须创建一个类。看看你的Json,这是你的 Person 类的简单实现。

public class Person {
private int code;
private String message;
private List<Data> data;

public int getCode() {
    return code;
}

public String getMessage() {
    return message;
}

public List<Data> getData() {
    return data;
}

public class Data {
    private int id;
    private String name;
    private String skills;
    private String image;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getSkills() {
        return skills;
    }

    public String getImage() {
        return image;
    }
}}

这就是您访问数据数组及其对象的方式。

for (int i = 0; i < cartList.size(); i++) {
                        for (Person.Data data : cartList.get(i).getData()) {
                            Log.d("TAG", "Name: " + data.getName() + ", Skill: " + data.getSkills() + ", Image: " + data.getImage() + ", id: " + data.getId());
                        }
                    }

这里我在Logcat中打印数据。确保在onResponse()块中执行此操作。

这就是完整代码的样子:

        requestQueue = Volley.newRequestQueue(this);
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
            URL,
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (response == null) {
                        Toast.makeText(getApplicationContext(), "Couldn't fetch the menu! Pleas try again.", Toast.LENGTH_LONG).show();
                        return;
                    }
                    Person persons = new Gson().fromJson(response.toString(), new TypeToken<Person>() {
                    }.getType());

                    // adding persons to cart list
                    cartList.clear();
                    cartList.add(persons);

                    for (int i = 0; i < cartList.size(); i++) {
                        for (Person.Data data : cartList.get(i).getData()) {
                            Log.d("TAG", "Name: " + data.getName() + ", Skill: " + data.getSkills() + ", Image: " + data.getImage() + ", id: " + data.getId());
                        }
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("error", error.toString());
                }
    });

    requestQueue.add(request);

希望这有帮助。