简体   繁体   中英

How to loop over an array of data that saved to a JSONObject and put it in a JSONArray?

I have fields in my HTML, say for example 2 rows of fields which I loop over on my controller.

I want it to result to something like this:

{
"specifications":
[
    {
      "name" : "height",
      "value" : "cm"
    },
    {
      "name" : "weight",
      "value" : "kg"
    }
  ]
}

But every time I loop using my code below, I only get the last row of the iteration saved to my JSONArray

JSONObject itemTypeObj = new JSONObject();
JSONArray itemTypeArray = new JSONArray();
JSONObject itemTypeSpecs = new JSONObject();
ArrayList<String> values = new ArrayList();

        for(int x = 0; x < specName.length; x++){

            itemTypeSpecs.put("specName", specName[x]);

            if (specValue[x].contains(",")) {

                for (String v : specValue[x].split(",")) {
                    values.add(v.trim());
                }

                itemTypeSpecs.put("specValue", values);
            } else {
                itemTypeSpecs.put("specValue", specValue[x]);
            }

            values.clear();

            itemTypeArray.put(itemTypeSpecs);

        }

itemTypeObj.put("specifications", itemTypeArray);

Result becomes like this instead of the one I expect from above

{"specifications":
  [
   {
    "name":"Weight",
    "value":"kg"
   },
   {
    "name":"Weight",
    "value":"kg"
   }
  ]
}

I can't find the reason why it's only getting the last row. Any help is appreciated. Thank you.

You should crate array list and JSONObject inside first "for loop".Because you change always same objects Can yo try this?

        JSONObject itemTypeObj = new JSONObject();
        JSONArray itemTypeArray = new JSONArray();

        for (int x = 0; x < specName.length; x++) {
            List<String> values = new ArrayList();
            JSONObject itemTypeSpecs = new JSONObject();
            itemTypeSpecs.put("specName", specName[x]);

            if (specValue[x].contains(",")) {
                for (String v : specValue[x].split(","))
                    values.add(v.trim());
                itemTypeSpecs.put("specValue", values);
            } else {
                itemTypeSpecs.put("specValue", specValue[x]);
            }
            itemTypeArray.put(itemTypeSpecs);
        }
        itemTypeObj.put("specifications", itemTypeArray);

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