简体   繁体   中英

Java looping over object

I am new to Java - and I am trying to loop through an JSONArray to create a "label", "value" array.

JSONArray records = (JSONArray) sch.get("schData");

looks like this A)

{"emotional distress":4,"peer difficulties":6,"behavioural difficulties":8,"kind and helpful behaviour":8,"overall stress":32,"_sdqID":11,"hyperactivity and concentration":6}

and I want to loop through this object to create the following structure

B)

"chart": [{
                  "label": "Overall Stress",
                  "value": 89
                },{
                  "label": "Emotional Stress",
                  "value": 1
                },{
                  "label": "Behavioural difficulties",
                  "value": 29
                },{
                  "label": "hyperactivity and concetration",
                  "value": 89
                },{
                  "label": "Getting along with others",
                  "value": 19
                },{
                  "label": "Keen and helpful behaviour",
                  "value": 99
                }]

--

so as I create a record I want to capitilize the key - and not include the _sdqID element. How do I do it?


I could try and create something manually.

    JSONObject row = new JSONObject();

    row.put("label", "Emotional Distress");
    row.put("value", ((JSONObject) records.get(i)).get("emotional distress"));

    rowArray.add(row);

and I tried to put this inside a 2nd loop - but I start to get cast issues inside this. So I am not sure what's the best approach at this step.

for (int j = 0; j < ((JSONObject) records.get(i)).size(); j++) {
//code
}

You can get the JSON array directly, and then loop through it.

import org.json.*;

public class JsonIO {

   public static void parseJson(StringBuffer sb){
   // sb is the JSON string
      JSONObject obj = new JSONObject(sb);

      JSONArray arr = obj.getJSONArray("chart");

      for (int i = 0; i< arr.length(); i++){
         // loop through
         System.out.println(arr.getJSONObject(i).getString("label")); // i.e
         System.out.println(arr.getJSONObject(i).getString("value"));
      }
   }

}

Secondly, GSON lib. can be used. Here you can download .

public static void parseJson(String sb){

 JsonParser jsonParser = new JsonParser();
 JsonObject jo = (JsonObject)jsonParser.parse(sb);
 JsonArray jArray = jo.getAsJsonArray("chart"); // get json array

 Gson gJson = new Gson();
 ArrayList jsonObjArrayList = gJson.fromJson(jArray, ArrayList.class);


 for (int i = 0; i< jsonObjArrayList.size(); i++){
    System.out.println(jsonObjArrayList.get(i).toString());
 }
}
public static void main(String[] args) {
    // TODO Auto-generated method stub
    JSONObject obj = new JSONObject();
    obj.put("emotional distress", 4);
    obj.put("peer difficulties", 6);
    obj.put("behavioural difficulties", 9);
    JSONArray array = new JSONArray();
    for(String key : obj.keySet()) {
        JSONObject newObj = new JSONObject();
        newObj.put("label", key);
        newObj.put("value", obj.get(key));
        array.put(newObj);
    }
    System.out.println(array);
}

Your A object is obj here and B is array .

You can use this code with some modification. I have changed the keys in output to Upper case you can write some according to you requirement.

public static void main(String[] args) {

    String data = "{\"emotional distress\":4,\"peer difficulties\":6,\"behavioural difficulties\":8,\"kind and helpful behaviour\":8,\"overall stress\":32,\"_sdqID\":11,\"hyperactivity and concentration\":6}";

    JSONObject json = new JSONObject();
    JSONArray chart = new JSONArray();
    json.put("chart", chart);
    JSONObject jsonObject = new JSONObject(data);
    Iterator<String> iterator = jsonObject.keys();
    while(iterator.hasNext()) {
        String key = iterator.next();
        if(key.equalsIgnoreCase("_sdqID")) {
            continue;
        }
        int value = jsonObject.getInt(key);
        key = key.toUpperCase();
        JSONObject row = new JSONObject();
        row.put("label", key);
        row.put("value", value);
        chart.put(row);
    }
}

Alankar you fixed it man, cheers. obj.keySet().iterator();" that will solve the problem. That's what I had to do to loop over the inner data.

ok so the variable sch looks like this

{"schData":[{"emotional distress":4,"peer difficulties":6,"behavioural difficulties":8,"kind and helpful behaviour":8,"overall stress":32,"_sdqID":11,"hyperactivity and concentration":6},{"emotional distress":4,"peer difficulties":8,"behavioural difficulties":6,"kind and helpful behaviour":5,"overall stress":28,"_sdqID":10,"hyperactivity and concentration":5},{"emotional distress":4,"peer difficulties":8,"behavioural difficulties":6,"kind and helpful behaviour":5,"overall stress":28,"_sdqID":9,"hyperactivity and concentration":5},{"emotional distress":2,"peer difficulties":2,"behavioural difficulties":4,"kind and helpful behaviour":2,"overall stress":13,"_sdqID":8,"hyperactivity and concentration":3},{"emotional distress":5,"peer difficulties":6,"behavioural difficulties":8,"kind and helpful behaviour":7,"overall stress":32,"_sdqID":7,"hyperactivity and concentration":6},{"emotional distress":7,"peer difficulties":6,"behavioural difficulties":8,"kind and helpful behaviour":9,"overall stress":34,"_sdqID":6,"hyperactivity and concentration":4},{"emotional distress":5,"peer difficulties":4,"behavioural difficulties":4,"kind and helpful behaviour":6,"overall stress":21,"_sdqID":5,"hyperactivity and concentration":2},{"emotional distress":1,"peer difficulties":0,"behavioural difficulties":0,"kind and helpful behaviour":0,"overall stress":1,"_sdqID":4,"hyperactivity and concentration":0}]}

here is the java code

JSONArray data = new JSONArray();

//System.out.println("sch" + sch);

JSONArray records  = (JSONArray) sch.get("schData");

for (int i = 0; i < records.size(); i++) {
    //code

    JSONObject chart = new JSONObject();

    JSONObject obj = (JSONObject) records.get(i);

    JSONArray rowArray = new JSONArray();
    for (Object key : obj.keySet()) {
        String keyStr = (String)key;
        Object keyvalue = obj.get(keyStr);

        //Print key and value
       // System.out.println("key: "+ keyStr + " value: " + keyvalue);

        JSONObject row = new JSONObject();


        row.put("label", keyStr);
        row.put("value", keyvalue);

        rowArray.add(row);
    }
    chart.put("chart", rowArray);



    JSONObject chartRecord = new JSONObject();
    chartRecord.put("title", "xxx");
    chartRecord.put("contents", chart);

    data.add(chartRecord);
}



//System.out.println("chart data: "+ data);

--- response is this

[{
    "contents": {
        "chart": [{
            "label": "emotional distress",
            "value": 4
        }, {
            "label": "peer difficulties",
            "value": 6
        }, {
            "label": "behavioural difficulties",
            "value": 8
        }, {
            "label": "kind and helpful behaviour",
            "value": 8
        }, {
            "label": "overall stress",
            "value": 32
        }, {
            "label": "_sdqID",
            "value": 11
        }, {
            "label": "hyperactivity and concentration",
            "value": 6
        }]
    },
    "title": "xxx"
}, {
    "contents": {
        "chart": [{
            "label": "emotional distress",
            "value": 4
        }, {
            "label": "peer difficulties",
            "value": 8
        }, {
            "label": "behavioural difficulties",
            "value": 6
        }, {
            "label": "kind and helpful behaviour",
            "value": 5
        }, {
            "label": "overall stress",
            "value": 28
        }, {
            "label": "_sdqID",
            "value": 10
        }, {
            "label": "hyperactivity and concentration",
            "value": 5
        }]
    },
    "title": "xxx"
}, {
    "contents": {
        "chart": [{
            "label": "emotional distress",
            "value": 4
        }, {
            "label": "peer difficulties",
            "value": 8
        }, {
            "label": "behavioural difficulties",
            "value": 6
        }, {
            "label": "kind and helpful behaviour",
            "value": 5
        }, {
            "label": "overall stress",
            "value": 28
        }, {
            "label": "_sdqID",
            "value": 9
        }, {
            "label": "hyperactivity and concentration",
            "value": 5
        }]
    },
    "title": "xxx"
}, {
    "contents": {
        "chart": [{
            "label": "emotional distress",
            "value": 2
        }, {
            "label": "peer difficulties",
            "value": 2
        }, {
            "label": "behavioural difficulties",
            "value": 4
        }, {
            "label": "kind and helpful behaviour",
            "value": 2
        }, {
            "label": "overall stress",
            "value": 13
        }, {
            "label": "_sdqID",
            "value": 8
        }, {
            "label": "hyperactivity and concentration",
            "value": 3
        }]
    },
    "title": "xxx"
}, {
    "contents": {
        "chart": [{
            "label": "emotional distress",
            "value": 5
        }, {
            "label": "peer difficulties",
            "value": 6
        }, {
            "label": "behavioural difficulties",
            "value": 8
        }, {
            "label": "kind and helpful behaviour",
            "value": 7
        }, {
            "label": "overall stress",
            "value": 32
        }, {
            "label": "_sdqID",
            "value": 7
        }, {
            "label": "hyperactivity and concentration",
            "value": 6
        }]
    },
    "title": "xxx"
}, {
    "contents": {
        "chart": [{
            "label": "emotional distress",
            "value": 7
        }, {
            "label": "peer difficulties",
            "value": 6
        }, {
            "label": "behavioural difficulties",
            "value": 8
        }, {
            "label": "kind and helpful behaviour",
            "value": 9
        }, {
            "label": "overall stress",
            "value": 34
        }, {
            "label": "_sdqID",
            "value": 6
        }, {
            "label": "hyperactivity and concentration",
            "value": 4
        }]
    },
    "title": "xxx"
}, {
    "contents": {
        "chart": [{
            "label": "emotional distress",
            "value": 5
        }, {
            "label": "peer difficulties",
            "value": 4
        }, {
            "label": "behavioural difficulties",
            "value": 4
        }, {
            "label": "kind and helpful behaviour",
            "value": 6
        }, {
            "label": "overall stress",
            "value": 21
        }, {
            "label": "_sdqID",
            "value": 5
        }, {
            "label": "hyperactivity and concentration",
            "value": 2
        }]
    },
    "title": "xxx"
}, {
    "contents": {
        "chart": [{
            "label": "emotional distress",
            "value": 1
        }, {
            "label": "peer difficulties",
            "value": 0
        }, {
            "label": "behavioural difficulties",
            "value": 0
        }, {
            "label": "kind and helpful behaviour",
            "value": 0
        }, {
            "label": "overall stress",
            "value": 1
        }, {
            "label": "_sdqID",
            "value": 4
        }, {
            "label": "hyperactivity and concentration",
            "value": 0
        }]
    },
    "title": "xxx"
}]

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