سؤال

I need to transform my data in a ArrayList to a JSON file, and I use JSON.simple. Everything is fine except one little thing that I want to get a result like ...... {source:0, target:1},{source:0, target:1},{source:0, target:2},{source:0, target:3} ...... but it returns ......{source:0, target:16},{source:0, target:16},{source:0, target:16}...... . My solution.size() is 17. Here is my code:

        JSONObject jsonObject = new JSONObject();
        JSONObject jsonNodesObject = new JSONObject();
        JSONObject jsonEdgesObject = new JSONObject();
        JSONArray jsonNodesArray = new JSONArray();
        JSONArray jsonEdgesArray = new JSONArray();

        String instString = solutions.get(0).get("institution");
        jsonNodesObject.put("name", instString);
        // extract name and institution from ArrayList
        for (int i = 0; i < solutions.size(); i++)
        {
            HashMap<String, String> eleHashMap= solutions.get(i);
            String nameString = eleHashMap.get("name");
            jsonNodesObject.put("name", nameString);
            jsonNodesArray.add(jsonNodesObject);
            jsonEdgesObject.put("source", 0);
            jsonEdgesObject.put("target", i);
            jsonEdgesArray.add(jsonEdgesObject);
        }
        jsonObject.put("nodes", jsonNodesArray);
        jsonObject.put("edges", jsonEdgesArray);
        System.out.println(jsonObject);

It seems that in every for loop, it refreshes the value of target: i of all my jsonEdgesArray.

Dose anyone know how to fix this? Thanks in advance!

هل كانت مفيدة؟

المحلول

As your iterating jsonNodesObject in for loop, same value will be put for jsonNodesObject.put("name", nameString); u have to initialize JSONObject jsonNodesObject = new JSONObject(); inside for loop

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top