1

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

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

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

我的json文件

{
  "code": 1200,
  "message": "Data Retrieved",
  "data": [
    {
      "id": 1,
      "name": "Vangipurapu Venkata Sai Laxman",
      "skills": "Cricketer, Batsman",
      "image": "https://qph.ec.quoracdn.net/main-qimg-4f5029c4319b41270f5643d461979645-c"
    },
    {
      "id": 2,
      "name": "Himesh Reshammiya",
      "skills": "music director, singer, producer, lyricist, distributor and actor",
      "image": "https://starsunfolded-1ygkv60km.netdna-ssl.com/wp-content/uploads/2016/01/Himesh-Reshammiya-nasal-singing.jpg"
    }
]
}

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

4

3 回答 3

0

您需要解析整个 JSON 响应,而不仅仅是“数据”属性。用于解析它的 GSON 文件可能看起来像这样:

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

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

于 2018-02-07T14:22:52.323 回答
0

您可以使用此链接将您的 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;
}

}
于 2018-02-07T14:36:43.110 回答
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 object而不是json array

现在,Gson的工作方式是它需要一个类来“映射”接收到的Json。因此,您必须创建一个类。查看您的 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);

希望这可以帮助。

于 2018-02-07T15:32:13.880 回答