Java 如何创建多个JSON数组
我一直在寻找创建JSON的方法,结果是 { “年龄”:100岁, “名称”:“mkyong.com”, “消息”:[“消息1”、“消息2”、“消息3”] } 但我想要一个这样的10倍数组Java 如何创建多个JSON数组,java,json,Java,Json,我一直在寻找创建JSON的方法,结果是 { “年龄”:100岁, “名称”:“mkyong.com”, “消息”:[“消息1”、“消息2”、“消息3”] } 但我想要一个这样的10倍数组 { "engine": "Trident", "browser": "Internet Explorer 4.0", "platform": "Win 95+", }, { "engine": "Trident",
{
"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+",
},
这就是我尝试的方式
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);
}
}
在下面的代码中
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);
}
JSONObject obj=null;
obj=新的JSONObject();
对于(int i=0;i您可以这样做:
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);
JSONObject JSONObject=new JSONObject();
JSONArray数组=新的JSONArray();
对于(int i=0;i您想要一个JSON数组,但您使用的是一个JSONObject
。@SotiriosDelimanolis感谢您的回复。如何创建类似example@Deepak正如建议的那样:创建JSONArray
并将你想做的事情添加到其中。如果你说我可以在答案中解释逻辑的话,我也会这么做。这种逻辑就像创建一个列表一样然后每次都在列表中添加一个新项目。谢谢你的回答。但是我不明白你的意思。你能举个例子吗?@Deepak你不明白什么?如果你不明白你在做什么,举个例子是没有帮助的。@Deepak很好。我建议你通过JSON支持的测试。我没有足够的声誉我很乐意投票支持你的答案,但我保证以后有答案时我会这样做。再次感谢你的支持answer@deepak别担心。但请不要马上要求解决方案。试着理解你正在做什么和你正在尝试做什么。解决方案通常会自动出现。JSONArray
没有put
me方法。检查此项,您将找到put
方法。是的,它没有put方法,但当我将其更改为add时,它起了作用。很抱歉,我没有足够的声誉来升级array.put(obj);
应该是array.add(obj)
@Sotirios Delimanolis:谢谢你提醒我刚刚更新了我的答案。除了放置
和添加
之外,这两个代码都是相同的。
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);