我在我的Android应用上显示了产品的列表视图。我正在使用返回JSON的Web服务。早些时候,我只展示了一份平面产品清单。但是现在对于每个列表,我必须添加一个带有JSON中variants
值的微调器。我该如何实现?
我目前的代码给我下面的错误
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 168 path $[0].variants
下面是我的代码:
JSON响应
{
"responce": "true",
"top_selling_product": [
{
"product_id": "10",
"product_name": "Palm Ruchi (Pack of 10)",
"product_name_arb": "",
"product_description_arb": "",
"category_id": "8",
"product_description": "",
"variants": [
{
"variant_id": "7",
"variant_name": "2L",
"in_stock": "0",
"price": "120",
"mrp": "130",
"unit_value": "25"
},
{
"variant_id": "8",
"variant_name": "5L",
"in_stock": "1",
"price": "240",
"mrp": "255",
"unit_value": "25"
},
{
"variant_id": "9",
"variant_name": "10L",
"in_stock": "1",
"price": "0",
"mrp": "0",
"unit_value": "0"
}
],
"product_image": "product-placeholder2.jpg",
"status": "",
"unit": "Box",
"increament": "0",
"rewards": "0",
"stock": "",
"title": "Oil"
},
{
"product_id": "11",
"product_name": "Sunflower Sunrich 1 ltr Box(pack of 10)",
"product_name_arb": "",
"product_description_arb": "",
"category_id": "8",
"product_description": "",
"variants": [],
"product_image": "product-placeholder3.jpg",
"status": "",
"unit": "Box",
"increament": "0",
"rewards": "0",
"stock": "",
"title": "Oil"
},
{
"product_id": "26",
"product_name": "TestName4",
"product_name_arb": "",
"product_description_arb": "",
"category_id": "8",
"product_description": "TestAddress4",
"variants": [],
"product_image": "img8",
"status": "",
"unit": "kg",
"increament": "1",
"rewards": "20",
"stock": "",
"title": "Oil"
}
]
}
Top_Selling_model.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Top_Selling_model implements Serializable {
@SerializedName("product_id")
@Expose
private String productId;
@SerializedName("product_name")
@Expose
private String productName;
@SerializedName("product_name_arb")
@Expose
private String productNameArb;
@SerializedName("product_description_arb")
@Expose
private String productDescriptionArb;
@SerializedName("category_id")
@Expose
private String categoryId;
@SerializedName("product_description")
@Expose
private String productDescription;
@SerializedName("variants")
@Expose
private List<VariantsModel> variants = null;
@SerializedName("product_image")
@Expose
private String productImage;
@SerializedName("status")
@Expose
private String status;
@SerializedName("unit")
@Expose
private String unit;
@SerializedName("increament")
@Expose
private String increament;
@SerializedName("rewards")
@Expose
private String rewards;
@SerializedName("stock")
@Expose
private String stock;
@SerializedName("title")
@Expose
private String title;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductNameArb() {
return productNameArb;
}
public void setProductNameArb(String productNameArb) {
this.productNameArb = productNameArb;
}
public String getProductDescriptionArb() {
return productDescriptionArb;
}
public void setProductDescriptionArb(String productDescriptionArb) {
this.productDescriptionArb = productDescriptionArb;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public List<VariantsModel> getVariants() {
return variants;
}
public void setVariants(List<VariantsModel> variants) {
this.variants = variants;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getIncreament() {
return increament;
}
public void setIncreament(String increament) {
this.increament = increament;
}
public String getRewards() {
return rewards;
}
public void setRewards(String rewards) {
this.rewards = rewards;
}
public String getStock() {
return stock;
}
public void setStock(String stock) {
this.stock = stock;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Variants_model.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class VariantsModel implements Serializable {
@SerializedName("variant_id")
@Expose
private String variantId;
@SerializedName("variant_name")
@Expose
private String variantName;
@SerializedName("in_stock")
@Expose
private String inStock;
@SerializedName("price")
@Expose
private String price;
@SerializedName("mrp")
@Expose
private String mrp;
@SerializedName("unit_value")
@Expose
private String unitValue;
public String getVariantId() {
return variantId;
}
public void setVariantId(String variantId) {
this.variantId = variantId;
}
public String getVariantName() {
return variantName;
}
public void setVariantName(String variantName) {
this.variantName = variantName;
}
public String getInStock() {
return inStock;
}
public void setInStock(String inStock) {
this.inStock = inStock;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getMrp() {
return mrp;
}
public void setMrp(String mrp) {
this.mrp = mrp;
}
public String getUnitValue() {
return unitValue;
}
public void setUnitValue(String unitValue) {
this.unitValue = unitValue;
}
}
Top_selling_Adapter.java
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.ArrayList;
import java.util.List;
import Config.BaseURL;
import Model.Top_Selling_model;
import gogrocer.tcc.R;
import static android.content.Context.MODE_PRIVATE;
public class Top_Selling_Adapter extends RecyclerView.Adapter<Top_Selling_Adapter.MyViewHolder> {
private List<Top_Selling_model> modelList;
ArrayList<String> variantsData = new ArrayList<>();
private Context context;
SharedPreferences preferences;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView product_nmae, product_prize;
public ImageView image;
public Spinner spinner;
public MyViewHolder(View view) {
super(view);
product_nmae = (TextView) view.findViewById(R.id.product_name);
product_prize = (TextView) view.findViewById(R.id.product_prize);
image = (ImageView) view.findViewById(R.id.iv_icon);
spinner=(Spinner) view.findViewById(R.id.variants);
}
}
public Top_Selling_Adapter(List<Top_Selling_model> modelList) {
this.modelList = modelList;
}
@Override
public Top_Selling_Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_top_selling, parent, false);
context = parent.getContext();
return new Top_Selling_Adapter.MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(Top_Selling_Adapter.MyViewHolder holder, int position) {
Top_Selling_model mList = modelList.get(position);
preferences = context.getSharedPreferences("lan", MODE_PRIVATE);
String language=preferences.getString("language","");
Glide.with(context)
.load(BaseURL.IMG_PRODUCT_URL + mList.getProduct_image())
.placeholder(R.drawable.icon)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.dontAnimate()
.into(holder.image);
// variantsData.add(mList.getVariants().getVariantName());
Log.e("Top_selling_array",mList.getVariants().getVariantName());
holder.product_prize.setText(context.getResources().getString(R.string.currency) + mList.getVariants().getPrice());
// Log.e("Top_selling_array",mList.getVariants().toString());
if (language.contains("english")) {
holder.product_nmae.setText(mList.getProduct_name());
}
else {
holder.product_nmae.setText(mList.getProduct_name_arb());
}
}
@Override
public int getItemCount() {
return modelList.size();
}
}
Home_fragment.java
private void make_top_selling() {
String tag_json_obj = "json_category_req";
ArrayList<VariantsModel> variantsList = new ArrayList<VariantsModel>();
isSubcat = false;
Map<String, String> params = new HashMap<String, String>();
params.put("parent", "");
isSubcat = true;
/* if (parent_id != null && parent_id != "") {
}*/
CustomVolleyJsonRequest jsonObjReq = new CustomVolleyJsonRequest(Request.Method.POST,
BaseURL.GET_TOP_SELLING_PRODUCTS, params, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
if (response != null && response.length() > 0) {
Boolean status = response.getBoolean("responce");
if (status) {
Gson gson = new Gson();
Type listType = new TypeToken<List<Top_Selling_model>>() {
}.getType();
Type listType2 = new TypeToken<List<VariantsModel>>() {
}.getType();
top_selling_models = gson.fromJson(response.getString("top_selling_product"), listType);
top_selling_adapter = new Top_Selling_Adapter(top_selling_models);
rv_top_selling.setAdapter(top_selling_adapter);
top_selling_adapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(getActivity(), getResources().getString(R.string.connection_time_out), Toast.LENGTH_SHORT).show();
}
}
});
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
retry,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
CustomVolleyJsonRequest.java
public class CustomVolleyJsonRequest extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private Map<String, String> params;
public CustomVolleyJsonRequest(String url, Map<String, String> params,
Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomVolleyJsonRequest(int method, String url, Map<String, String> params,
Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
编辑:更改了我的POJO类。
根据该JsonResponce,我认为您的模型存在问题。将您的json响应粘贴到此处https://jsoneditoronline.org,然后查看格式化的json,然后将json http://www.jsonschema2pojo.org粘贴到此处以创建模型。在http://www.jsonschema2pojo.org中,您必须选择目标语言Java,源类型为Json,注释样式Gson和预览。从那里获取模型,然后重试。
for (mList:mList){
for (variant : Variants){
variantList.add (variant)
}
}
首先创建一个字符串列表。
List<String> variantNameList = new ArrayList<String>();
for (mList:mList){
for (variant : Variants){
variantNameList.add (variant. variant_name)
}
}
这是您的列表,其中包含所有变体名称。然后您需要一个适配器
//为微调器创建适配器
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, variantNameList);
//下拉布局样式-带收音机的列表视图
buttondataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//将数据适配器连接到微调器
spinner.setAdapter(dataAdapter);
就是全部