Jean-Luc Palmyre Jean-Luc Palmyre - 1 year ago 79
Java Question

Json formatting for java

Hi i need to produce a json file with a certain format. I'm stuck and advice on how to proceed with this. My code is below:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import java.io.FileWriter;
import java.io.IOException;

public class Student {

public static void main(String[] args) {
int a = -7;
int b = 7;
int k = 103;
int order = 109;
int px = 60;
int py = 76;

JSONObject obj = new JSONObject();
obj.put("name", "JEAN-LUC PALMYRE");
obj.put("srn", "120299364");
obj.put("ecc","");



try (FileWriter file = new FileWriter("Jean-LucPalmyre_120299364_CO3326_cw1.json"))
{

file.write(obj.toJSONString());
file.flush();

} catch (IOException e) {
e.printStackTrace();
}

System.out.print(obj);

}


The output should be like this:

{
"name": "MARK ZUCKERBERG",
"srn": "000000001",
"ecc": {
"a": -2,
"b": 13,
"k": 103,
"order": 109
},

Answer Source

try this:

 JSONObject obj = new JSONObject();
 obj.put("name", "JEAN-LUC PALMYRE");
 obj.put("srn", "120299364");

 JSONObject objEcc = new JSONObject();
 objEcc.put("a",a);
 objEcc.put("b",b);
 objEcc.put("k",k);
 objEcc.put("order",order);

 obj.put("ecc",objEcc);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download