Tuesday, 10 September 2013

Error when using JSONSimple to write a json file with for loop

Error when using JSONSimple to write a json file with for loop

I need to 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!

No comments:

Post a Comment