简体   繁体   中英

JSON Arraylist HashMap Extraction Android

Please bear with me with this.Follow through the whole code.I will be putting everything just to be clear: 在此处输入图片说明

And this is my json : you can format here

https://jsonformatter.curiousconcept.com/

[{"productLineItemId":5,"restaurantId":2,"productId":5,"catalogName":"Cold Drink","categoryName":"sprite","subCategoryName":"SPRITE ","productName":"SPRITE","price":20.0,"optionName":"no","optionValues":"200ML","veg":true,"spicy":false},{"productLineItemId":8,"restaurantId":2,"productId":5,"catalogName":"veg","categoryName":"south indian","subCategoryName":"rice","productName":"jeera Rice","price":888.0,"optionName":"notning","optionValues":"ooo","veg":true,"spicy":true},{"productLineItemId":100,"restaurantId":2,"productId":5,"catalogName":"non veg","categoryName":"south indian","subCategoryName":"hot briyani","productName":"briyani","price":9.0,"optionName":"plate","optionValues":"half","veg":true,"spicy":true}]

Now Here ,you can see inside that json we have 3 objects right now,which in future will be dynamic,means could be many number.So, my goal is to retrieve all those Json Objects and show them in a custom adaptor list.

Below these are my codes: MainActivity.java

 try {
            httpClient2=new DefaultHttpClient();
            StringBuilder stringBuilder2=new StringBuilder("xxxxxxxx");
            httpPost2=new HttpPost(stringBuilder2.toString());
            httpResponse2=httpClient2.execute(httpPost2);

            code=httpResponse2.getStatusLine().getStatusCode();
            httpPost2.setHeader(HTTP.CONTENT_TYPE,"application/json");

            HttpEntity httpEntity2=httpResponse2.getEntity();

            if(code<200 && code>=300){
                Log.d("msg","Here <200 and >300");
            }
            else{


  if(httpEntity2!=null){
                    cena= EntityUtils.toString(httpEntity2);

                    JSONArray jsonArray=new JSONArray(cena);

                    hashMapArrayList=new ArrayList<HashMap<String,String>>();

                    for(int i=0;i<jsonArray.length();i++) {
                        jsonObject = jsonArray.getJSONObject(i);

                        HashMap<String, String> hashMap = new HashMap<String, String>();

                        hashMap.put("Price", jsonObject.getString("price"));
                        hashMap.put("CategoryName", jsonObject.getString("categoryName"));
                        hashMap.put("ProductName", jsonObject.getString("productName"));
                        hashMap.put("CatalogName", jsonObject.getString("catalogName"));

                        hashMapArrayList.add(hashMap);

                    }



                    Intent intent = new Intent(MainActivity.this, Checkout.class);

                    intent.putExtra("arrayhash",hashMapArrayList);
                    startActivity(intent);


                    Log.d("cena","got something here"+cena.toString());
                }

//Checkout.java

 listView=(ListView)findViewById(R.id.listView);


     hashMapArrayList2=(ArrayList<HashMap<String,String>>) getIntent().getSerializableExtra("arrayhash");


    price_a = new String[hashMapArrayList2.size()];
    categoryName_b = new String[hashMapArrayList2.size()];
    productName_c = new String[hashMapArrayList2.size()];
    catalogName_d = new String[hashMapArrayList2.size()];

    int i=0;
    for(Map<String,String> item:hashMapArrayList2){
        price_a[i]=item.get("Price");
        categoryName_b[i]=item.get("CategoryName");
        productName_c[i]=item.get("ProductName");
        catalogName_d[i]=item.get("CatalogName");
        i++;
    }



    customAdapter=new CustomAdapter(Checkout.this,price_a,categoryName_b,productName_c,catalogName_d);
    listView.setAdapter(customAdapter);

//This is my Custom Adaptor

public CustomAdapter(Context context,String price[],String categoryName[],String productName[],String catalogName[]){
    this.context=context;
    this.price=price;
    this.categoryName=categoryName;
    this.productName=productName;
    this.catalogName=catalogName;
}

@Override
public int getCount() {
    return price.length;
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {


    layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View v=layoutInflater.inflate(R.layout.custom_row,null);

    tv2=(TextView)v.findViewById(R.id.textView2);
    tv3=(TextView)v.findViewById(R.id.textView3);
    tv4=(TextView)v.findViewById(R.id.textView4);
    tv5=(TextView)v.findViewById(R.id.textView5);


    return v;
}

//So i Am getting output like this : 在此处输入图片说明

//Now You could see the problem,I have 3 json objects but I am getting only one which I am able to show.Could you show me where modificatiuons needs to be so that I could show all json objects(dynamic) in custom adapter.I hope you got the full understanding.And I am new to development and If I have done any mistakes then sorry,deeply appreciated.

After some modification suggested from comment section,I got these : Duplicate 在此处输入图片说明

Just modify your logic as below

 hashMapArrayList=new ArrayList<HashMap<String,String>>();

 JSONArray jsonArray=new JSONArray(cena);

    for(int i=0;i<jsonArray.length();i++) {

       jsonObject = jsonArray.getJSONObject(i);
       HashMap<String, String> hashMap = new HashMap<String, String>();
       hashMap.put("Price", jsonObject.getString("price"));
       hashMap.put("CategoryName", jsonObject.getString("categoryName"));
       hashMap.put("ProductName", jsonObject.getString("productName"));
       hashMap.put("CatalogName", jsonObject.getString("catalogName"));
       hashMapArrayList.add(hashMap);

    }

Just move HashMap<String, String> hashMap inside loop and add this one by one in hashMapArrayList

Modified code . Initialize ArrayList out of the for loop and inside the for loop add the HashMap into the ArrayList

     hashMapArrayList=new ArrayList<HashMap<String,String>>();

   JSONArray jsonArray=new JSONArray(cena);
    for(int i=0;i<jsonArray.length();i++) {
                            jsonObject = jsonArray.getJSONObject(i);
                        HashMap<String, String> hashMap = new HashMap<String, String>();


                        hashMap.put("Price", jsonObject.getString("price"));
                        hashMap.put("CategoryName", jsonObject.getString("categoryName"));
                        hashMap.put("ProductName", jsonObject.getString("productName"));
                        hashMap.put("CatalogName", jsonObject.getString("catalogName"));

                        hashMapArrayList.add(hashMap);
      }

Use Gson for the Parsing

@Generated("org.jsonschema2pojo") public class Example {

@SerializedName("productLineItemId")
@Expose
private Integer productLineItemId;
@SerializedName("restaurantId")
@Expose
private Integer restaurantId;
@SerializedName("productId")
@Expose
private Integer productId;
@SerializedName("catalogName")
@Expose
private String catalogName;
@SerializedName("categoryName")
@Expose
private String categoryName;
@SerializedName("subCategoryName")
@Expose
private String subCategoryName;
@SerializedName("productName")
@Expose
private String productName;
@SerializedName("price")
@Expose
private Double price;
@SerializedName("optionName")
@Expose
private String optionName;
@SerializedName("optionValues")
@Expose
private String optionValues;
@SerializedName("veg")
@Expose
private Boolean veg;
@SerializedName("spicy")
@Expose
private Boolean spicy;

/**
 * @return The productLineItemId
 */
public Integer getProductLineItemId() {
    return productLineItemId;
}

/**
 * @param productLineItemId The productLineItemId
 */
public void setProductLineItemId(Integer productLineItemId) {
    this.productLineItemId = productLineItemId;
}

/**
 * @return The restaurantId
 */
public Integer getRestaurantId() {
    return restaurantId;
}

/**
 * @param restaurantId The restaurantId
 */
public void setRestaurantId(Integer restaurantId) {
    this.restaurantId = restaurantId;
}

/**
 * @return The productId
 */
public Integer getProductId() {
    return productId;
}

/**
 * @param productId The productId
 */
public void setProductId(Integer productId) {
    this.productId = productId;
}

/**
 * @return The catalogName
 */
public String getCatalogName() {
    return catalogName;
}

/**
 * @param catalogName The catalogName
 */
public void setCatalogName(String catalogName) {
    this.catalogName = catalogName;
}

/**
 * @return The categoryName
 */
public String getCategoryName() {
    return categoryName;
}

/**
 * @param categoryName The categoryName
 */
public void setCategoryName(String categoryName) {
    this.categoryName = categoryName;
}

/**
 * @return The subCategoryName
 */
public String getSubCategoryName() {
    return subCategoryName;
}

/**
 * @param subCategoryName The subCategoryName
 */
public void setSubCategoryName(String subCategoryName) {
    this.subCategoryName = subCategoryName;
}

/**
 * @return The productName
 */
public String getProductName() {
    return productName;
}

/**
 * @param productName The productName
 */
public void setProductName(String productName) {
    this.productName = productName;
}

/**
 * @return The price
 */
public Double getPrice() {
    return price;
}

/**
 * @param price The price
 */
public void setPrice(Double price) {
    this.price = price;
}

/**
 * @return The optionName
 */
public String getOptionName() {
    return optionName;
}

/**
 * @param optionName The optionName
 */
public void setOptionName(String optionName) {
    this.optionName = optionName;
}

/**
 * @return The optionValues
 */
public String getOptionValues() {
    return optionValues;
}

/**
 * @param optionValues The optionValues
 */
public void setOptionValues(String optionValues) {
    this.optionValues = optionValues;
}

/**
 * @return The veg
 */
public Boolean getVeg() {
    return veg;
}

/**
 * @param veg The veg
 */
public void setVeg(Boolean veg) {
    this.veg = veg;
}

/**
 * @return The spicy
 */
public Boolean getSpicy() {
    return spicy;
}

/**
 * @param spicy The spicy
 */
public void setSpicy(Boolean spicy) {
    this.spicy = spicy;
}

}

Example exampleObj = new Example();

Gson gson = new Gson();
JsonArray jsonArray = new JsonArray(response.string);

exampleObj=gson.fromJson(response.string,Example.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM