Reputation: 667
I am using json simple to handle json array in java. This is the code below:
JSONObject job=new JSONObject();
try{job.put("roll-no",Integer.parseInt(rollnoprompt.getText()));}
catch(Exception e){}
JSONArray Marks=new JSONArray();
for(int i=0;i<mrkcls.size();++i){
JSONObject job1=new JSONObject();
job1.put("Question-no",i+1);
job1.put("total-marks",Float.parseFloat(mrkcls.get(i).questionMarks.getText()));
JSONArray Parts=new JSONArray();
char ch=97;
java.util.List<JTextField> partsMarksList=mrkcls.get(i).partsMarks;
for(int j=0;j<partsMarksList.size();++j){
JSONObject job2=new JSONObject();
job2.put("part",Character.toString(ch));
job2.put("marks",Float.parseFloat(partsMarksList.get(j).getText()));
++ch;
Parts.add(job2);
}
job1.put("Parts",Parts);
Marks.add(job1);
}
job.put("Marks",Marks);
reportCard.add(job);
//System.out.println(job);
FileWriter file=new FileWriter("Result.json");
file.write(reportCard.toJSONString());
file.flush();
file.close();
I notice that the json array in file Result.json is written in a straight line, something like this:
[{"roll-no":1,"Marks":[{"Parts":[{"part":"a","marks":2.0},{"part":"b","marks":1.0},{"part":"c","marks":2.0}],"Question-no":1,"total-marks":5.0},{"Parts":[{"part":"a","marks":2.0},{"part":"b","marks":2.0}],"Question-no":2,"total-marks":4.0},{"Parts":[],"Question-no":3,"total-marks":4.0},{"Parts":[{"part":"a","marks":2.0},{"part":"b","marks":2.0}],"Question-no":4,"total-marks":4.0}]}]
Definitely I am going to read this file again from a program, still this format doesn't looks good. I want this format:
[{
"roll-no":1
"Marks":[{
"Question-no":1,
"total-marks":6,
"Parts":[{
"Question-no":"a",
"Marks":2
},{
"Question-no":"b",
"Marks":2
},{
"Question-no":"c",
"Marks":2
}]
},{
"Question-no":2,
"total-marks":5,
"Parts":[]
},{
"Question-no":3,
"total-marks":5,
"Parts":[]
}]
}]
I remember using a pretty()
method in mongodb for achieving this, is there any similar method in java?
Would really appreciate any help!
Thank you.
Upvotes: 0
Views: 95
Reputation: 7205
If you are using org.json.JSONObject
You can set the indentFactor
i.e The number of spaces to add to each level of indentation,
reportCard.add(job.toString(4));
Note that, it is available in org.json
not in org.json.simple
Upvotes: 0
Reputation: 2707
Use this while initializing your object mapper
mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
Upvotes: 0