gpt4 book ai didi

java - 使用 JSON.simple 创建带有键和值的对象和数组

转载 作者:行者123 更新时间:2023-12-03 01:20:56 26 4
gpt4 key购买 nike

我刚刚选择了 JSON.simple - 一个简单的 JSON Java 工具包,位于 https://code.google.com/p/json-simple/ 。我需要创建带有 key => value 的 Json 数组,而不仅仅是值字符串。例如,我有下面的代码

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

public class JsonSimpleExample {
public static void main(String[] args) {

JSONObject obj = new JSONObject();
obj.put("name", "mkyong.com");
obj.put("age", new Integer(100));

JSONArray list = new JSONArray();
list.add("msg 1");
list.add("msg 2");
list.add("msg 3");

obj.put("messages", list);
}
}

产生:

{
"age":100,
"name":"mkyong.com",
"messages":[
"msg 1",
"msg 2",
"msg 3"
]
}

现在我需要创建一个 Json 对象和带有 key => value 的数组,而不仅仅是 String 作为值。就像下面这样:

{
"age":100,
"name":"mkyong.com",
"messages":[
{
"msg1" : "1",
"msg2" : "2",
"msg3" : "3"
}
]
}

请问我怎样才能实现这个目标?谢谢

最佳答案

为此,您还需要 2 个 JSONObject,并且还需要提供要放入数组中的对象的键。示例;

JSONObject obj = new JSONObject();
obj.put("name", "mkyong.com");
obj.put("age", new Integer(100));

JSONArray list = new JSONArray();
JSONObject obj2 = new JSONObject();
JSONObject obj3 = new JSONObject();
obj3.put("msg 1","1");
obj3.put("msg 2","2");
obj3.put("msg 3","3");
obj2.put("obj3",obj3);
list.put(obj2);
obj.put("messages", list);

关于java - 使用 JSON.simple 创建带有键和值的对象和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33365983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com