Reputation: 195
I was looking this for creating JSON and the output is
{ "age":100, "name":"mkyong.com", "messages":["msg 1","msg 2","msg 3"] }
But i want an array of 10 times like this
{
"engine": "Trident",
"browser": "Internet Explorer 4.0",
"platform": "Win 95+",
},
{
"engine": "Trident",
"browser": "Internet Explorer 5.0",
"platform": "Win 95+",
},
{
"engine": "Trident",
"browser": "Internet Explorer 5.5",
"platform": "Win 95+",
},
And this is the way I tried
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class TestJson {
public static void main(String[] args) {
JSONObject obj=null;
obj = new JSONObject();
for(int i=0;i<10;i++)
{
obj.put("engine", "mkyong.com");
obj.put("browser", i);
obj.put("platform", i);
//obj.put("messages", list);
}
try {
FileWriter file = new FileWriter("c:\\test.json");
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(obj);
}
}
but this only prints 1 json
{
"engine": "Trident",
"browser": "Internet Explorer 4.0",
"platform": "Win 95+",
}
Upvotes: 0
Views: 6609
Reputation: 12961
you can do this:
JSONObject jsonObject = new JSONObject();
JSONArray array = new JSONArray();
for(int i=0;i<10;i++){
JSONObject obj = new JSONObject();
obj.put("engine", "mkyong.com");
obj.put("browser", i);
obj.put("platform", i);
//if you are using JSON.simple do this
array.add(obj);
//and if you use json-jena
array.put(obj);
}
jsonObject.put("MyArray" , array);
System.out.print(jsonObject);
Upvotes: 2
Reputation: 280177
In the following code
JSONObject obj=null;
obj = new JSONObject();
for(int i=0;i<10;i++)
{
obj.put("engine", "mkyong.com");
obj.put("browser", i);
obj.put("platform", i);
//obj.put("messages", list);
}
you are creating a single JSONObject
and overwriting its values 10 times.
Why are you working with a JSONObject
when you want a JSON array?
Create a JSONArray
and add 10 JSONObject
objects to it.
Upvotes: 0