【问题标题】:How to fetch all API data using Gson volley in android如何在 android 中使用 Gson volley 获取所有 API 数据
【发布时间】:2018-12-10 12:56:14
【问题描述】:

看看我的 API 数据:

 {
            "items": [
        {
                    "id": 2,
                    "sku": "Beige and blue jacquard and chiffon embroidered saree & Blouse",
                    "name": "Beige and blue jacquard and chiffon embroidered saree & Blouse",
                    "attribute_set_id": 4,
                    "price": 25.5,
                    "status": 1,
                    "visibility": 4,
                    "type_id": "simple",
                    "created_at": "2018-04-25 08:52:58",
                    "updated_at": "2018-05-23 19:00:20",
                    "product_links": [],
                    "tier_prices": [],
                    "custom_attributes": [

                        {
                            "attribute_code": "image",
                            "value": "/6/7/6759_original_1.jpg"
                        },
                       {
                        "attribute_code": "category_ids",
                        "value": [
                            "5",
                            "13"
                        ]
                    }
                    ]
                }
        ],
            "search_criteria": {
                "filter_groups": []
            },
            "total_count": 574
        }

我的模型看起来像这样:

-----------------------------------com.example

.apidata.models.CustomAttribute.java-----------------------------------

package com.example.apidata.models;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class CustomAttribute {

@SerializedName("attribute_code")
@Expose
private String attributeCode;
@SerializedName("value")
@Expose
private String value;

/**
* No args constructor for use in serialization
* 
*/
public CustomAttribute() {
}

/**
* 
* @param attributeCode
* @param value
*/
public CustomAttribute(String attributeCode, String value) {
super();
this.attributeCode = attributeCode;
this.value = value;
}

public String getAttributeCode() {
return attributeCode;
}

public void setAttributeCode(String attributeCode) {
this.attributeCode = attributeCode;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

}
-----------------------------------com.example.apidata.models.Item.java-----------------------------------

package com.example.apidata.models;

public class Item {

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("sku")
@Expose
private String sku;
@SerializedName("name")
@Expose
private String name;
@SerializedName("attribute_set_id")
@Expose
private Integer attributeSetId;
@SerializedName("price")
@Expose
private float price;
@SerializedName("status")
@Expose
private Integer status;
@SerializedName("visibility")
@Expose
private Integer visibility;
@SerializedName("type_id")
@Expose
private String typeId;
@SerializedName("created_at")
@Expose
private String createdAt;
@SerializedName("updated_at")
@Expose
private String updatedAt;
@SerializedName("product_links")
@Expose
private List<Object> productLinks = null;
@SerializedName("tier_prices")
@Expose
private List<Object> tierPrices = null;
@SerializedName("custom_attributes")
@Expose
private List<Object> customAttributes = null;

/**
 * No args constructor for use in serialization
 *
 */
public Item() {
}

/**
 *
 * @param productLinks
 * @param updatedAt
 * @param id
 * @param price
 * @param attributeSetId
 * @param visibility
 * @param status
 * @param createdAt
 * @param name
 * @param tierPrices
 * @param sku
 * @param typeId
 * @param customAttributes
 */
public Item(Integer id, String sku, String name, Integer attributeSetId, Integer price, Integer status, Integer visibility, String typeId, String createdAt, String updatedAt, List<Object> productLinks, List<Object> tierPrices, List<Object> customAttributes) {
    super();
    this.id = id;
    this.sku = sku;
    this.name = name;
    this.attributeSetId = attributeSetId;
    this.price = price;
    this.status = status;
    this.visibility = visibility;
    this.typeId = typeId;
    this.createdAt = createdAt;
    this.updatedAt = updatedAt;
    this.productLinks = productLinks;
    this.tierPrices = tierPrices;
    this.customAttributes = customAttributes;
}

public Integer getId() {
    return id;
}

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

public String getSku() {
    return sku;
}

public void setSku(String sku) {
    this.sku = sku;
}

public String getName() {
    return name;
}

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

public Integer getAttributeSetId() {
    return attributeSetId;
}

public void setAttributeSetId(Integer attributeSetId) {
    this.attributeSetId = attributeSetId;
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public Integer getStatus() {
    return status;
}

public void setStatus(Integer status) {
    this.status = status;
}

public Integer getVisibility() {
    return visibility;
}

public void setVisibility(Integer visibility) {
    this.visibility = visibility;
}

public String getTypeId() {
    return typeId;
}

public void setTypeId(String typeId) {
    this.typeId = typeId;
}

public String getCreatedAt() {
    return createdAt;
}

public void setCreatedAt(String createdAt) {
    this.createdAt = createdAt;
}

public String getUpdatedAt() {
    return updatedAt;
}

public void setUpdatedAt(String updatedAt) {
    this.updatedAt = updatedAt;
}

public List<Object> getProductLinks() {
    return productLinks;
}

public void setProductLinks(List<Object> productLinks) {
    this.productLinks = productLinks;
}

public List<Object> getTierPrices() {
    return tierPrices;
}

public void setTierPrices(List<Object> tierPrices) {
    this.tierPrices = tierPrices;
}

public List<Object> getCustomAttributes() {
    return customAttributes;
}

public void setCustomAttributes(List<Object> customAttributes) {
    this.customAttributes = customAttributes;
}

} ------------------------------------com.example.apidata.models.Result.java---- -------------------------------------------

package com.example.apidata.models;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Result {

@SerializedName("items")
@Expose
private List<Item> items = null;
@SerializedName("search_criteria")
@Expose
private SearchCriteria searchCriteria;
@SerializedName("total_count")
@Expose
private Integer totalCount;

/**
* No args constructor for use in serialization
* 
*/
public Result() {
}

/**
* 
* @param totalCount
* @param searchCriteria
* @param items
*/
public Result(List<Item> items, SearchCriteria searchCriteria, Integer totalCount) {
super();
this.items = items;
this.searchCriteria = searchCriteria;
this.totalCount = totalCount;
}

public List<Item> getItems() {
return items;
}

public void setItems(List<Item> items) {
this.items = items;
}

public SearchCriteria getSearchCriteria() {
return searchCriteria;
}

public void setSearchCriteria(SearchCriteria searchCriteria) {
this.searchCriteria = searchCriteria;
}

public Integer getTotalCount() {
return totalCount;
}

public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}

}
-----------------------------------com.example.apidata.models.SearchCriteria.java-----------------------------------

package com.example.apidata.models;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class SearchCriteria {

@SerializedName("filter_groups")
@Expose
private List<Object> filterGroups = null;

/**
* No args constructor for use in serialization
* 
*/
public SearchCriteria() {
}

/**
* 
* @param filterGroups
*/
public SearchCriteria(List<Object> filterGroups) {
super();
this.filterGroups = filterGroups;
}

public List<Object> getFilterGroups() {
return filterGroups;
}

public void setFilterGroups(List<Object> filterGroups) {
this.filterGroups = filterGroups;
}

}

我正在使用适配器在回收站视图中获取数据,但它给出的错误如下:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 应为 BEGIN_ARRAY,但在第 1 行第 408 列路径为 STRING $.items[0].custom_attributes[0].value

它给了我“items”数组的值,但它没有给出“custom_attributes”数组的值,它实际上在“数组中>项目

这是我的适配器类:

public class Adapter extends RecyclerView.Adapter{

    private Context context;
    private List<Item> data = Collections.emptyList();
    public Adapter(List<Item> data)
    {
        this.data = data;

    }


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(R.layout.grid,parent,false);
        return new ProgrammingViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

      final Item result = data.get(position);

      ((ProgrammingViewHolder)holder).name.setText(result.getName());
        ((ProgrammingViewHolder)holder).price.setText((int) result.getPrice());
((ProgrammingViewHolder)holder).image.setText(result.getCustomAttributes().toArray(););



    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public class ProgrammingViewHolder extends RecyclerView.ViewHolder{

        TextView name, price;
        ImageView image;

        public ProgrammingViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.textView1);
            price = itemView.findViewById(R.id.textView2);
            image = itemView.findViewById(R.id.imageView);

        }
    }
}

MainActivity.java:

 RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

        stringRequest = new StringRequest(Request.Method.GET, URL_DATA, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d("response", response);

                results = gson.fromJson(response, Result.class);


                data = results.getItems();
                Log.d("data", String.valueOf(data));

              adapter  =  new Adapter(data);
               programming_list.setAdapter(adapter);



            }
        }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();

                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/json; charset=utf-8");
                    headers.put("Authorization",  "API KEY");
                    return headers;
                }
        };

        requestQueue.add(stringRequest);

所以,请帮我获取数组“custom_attributes”的值

【问题讨论】:

  • custom_attributes 是 List.you 可以获得值 items.get(POSITION).getCustom_attributes.get(POSITION).getAttribute_code();
  • 您的实际问题在 Result.class-->Item.Class 它的一行修复...您能发布您的 Result.class 和 Item.Class 吗?所以我可以告诉你你必须在哪里改变你的代码
  • @Mortuza Shahariar:我试图使用 Gson 获取数据,但失败了。数据不是来自适配器中的 Gson。我怎样才能得到它。
  • @AkshaySonavadekar 看看我的回答是否有帮助

标签: android android-studio gson android-volley android-recyclerview


【解决方案1】:

根据您提供的 JSON value 键不包含特定对象。它的值取决于attribute_code

所以你的 CustomAttribute 类应该是这样的

public class CustomAttribute {
    @SerializedName("attribute_code")
    @Expose
    private String attributeCode;
    @SerializedName("value")
    @Expose
    private Object value;
}

然后根据 attributeCode 转换你的值对象。

【讨论】:

    【解决方案2】:

    理想情况下,您的 Result.class 应该是这样的

    @SerializedName("items")
    ArrayList<Items> itemsList;
    .
    .
    .
    your other fields will be here
    .
    .
    .
    .
    

    那么你的 Items.class 应该是这样的

    @SerializedName("id")
    String id;
    .
    .
    .
    .
    your other fields will be here
    .
    .
    .
    .
    @SerializedName("product_links")
    ArrayList<ProductLinks>productLinksList;
    @SerializedName("tier_prices")
    ArrayList<TierPrices>tierPricesList;
    @SerializedName("custom_attributes")
    ArrayList<CustomAttirbutes>customAttributesList;
    

    您的问题可能在 Items.class 中,您使用 customAttributeList 作为字符串变量而不是 ArrayList。

    在将您的 volley API 响应对象分配给您的 result.class 时。 您的结果对象应该与您的截击响应对象完全映射,以防匹配失败。这会导致此问题。

    【讨论】:

    • 我仍然没有在适配器上设置数据。有什么办法可以让我在上面提到的适配器类中访问“custom_attributes”数组的数据。
    • @AkshaySonavadekar 请在 reuslt 下发布您的 result.calss 和其他模型类。类,那么只有我可以通过查看您的代码来提供帮助...尝试使用 result.class 和它下的其他类来编辑您的问题
    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 2019-03-19
    • 2019-02-23
    • 2017-06-30
    • 2020-02-24
    • 2021-12-11
    • 1970-01-01
    • 2020-05-11
    相关资源
    最近更新 更多