I need to create a json like this
[
{
"name": "Michael Bruce",
"gender": "Male",
"designation": "System Architect"
},
{
"name": "Jennifer Winters",
"gender": "Female",
"designation": "Senior Programmer"
},
{
"name": "Donna Fox",
"gender": "Female",
"designation": "Office Manager"
},
{
"name": "Howard Hatfield",
"gender": "Male",
"designation": "Customer Support"
}
]
I tried to make it with this program ...
import java.io.PrintWriter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.io.FileWriter;
public class hello{
public static void getJSONArray() throws JSONException {
/* JSONArray jo= new JSONArray();
JSONObject obj1= new JSONObject();
obj1.put("A","a");
JSONObject obj2= new JSONObject();
obj2.put("B","b");
JSONObject obj3= new JSONObject();
obj3.put("B","c");
jo.put(obj1);
jo.put(obj2);
jo.put(obj3);
System.out.println(jo.toString());*/
/*-----------------------------*/
JSONObject mainObj = new JSONObject();
for(int p=0;p<5;p++){
JSONObject jo1= new JSONObject ();
String strr= Integer.toString(p);
String strr2=Integer.toString(p+1);
jo1.put("name", strr );
jo1.put("gender", strr2);
jo1.put("designation",strr2);
JSONArray ja = new JSONArray();
ja.put(jo1);
mainObj.accumulate("employees", ja);
}
/*System.out.println(mainObj);
PrintWriter writer = new PrintWriter("neww.json", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();*/
try{
// create new file
String content = mainObj.toString();
String path="E:\\a\\hi.txt";
File file = new File(path);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// write in file
bw.write(content);
// close connection
bw.close();
}catch(Exception e){
System.out.println(e);
}
}
public static void main(String args[]) throws JSONException{
getJSONArray();
}
}
but i am getting json of the form as
{
"employees": [
[{
"gender": "1",
"name": "0",
"designation": "1"
}],
[{
"gender": "2",
"name": "1",
"designation": "2"
}],
[{
"gender": "3",
"name": "2",
"designation": "3"
}],
[{
"gender": "4",
"name": "3",
"designation": "4"
}],
[{
"gender": "5",
"name": "4",
"designation": "5"
}]
]
}
What change should i make in my java code to get the json of the type i have shown first.I have written my json to a file,. I tried this link How to create correct JsonArray in Java using JSONObject
But i am getting output as
{
"employees": [{
"gender": "5",
"name": "4",
"designation": "5"
}]
}