如何使用 JSONObject 在 Java 中创建正确的 JSONArray [英] How to create correct JSONArray in Java using JSONObject
问题描述
如何使用 JSONObject 在 Java 中创建如下所示的 JSON 对象?
how can I create a JSON Object like the following, in Java using JSONObject ?
{
"employees": [
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}
],
"manager": [
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}
]
}
我找到了很多例子,但不是我的 JSONArray 字符串.
I've found a lot of example, but not my exactly JSONArray string.
推荐答案
以下是一些使用 Java 6 的代码,可帮助您入门:
Here is some code using java 6 to get you started:
JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");
JSONArray ja = new JSONArray();
ja.put(jo);
JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);
由于在 put
和 add
之间存在很多混淆,我将尝试解释其中的区别.在 java 6 org.json.JSONArray 中包含 put
方法和在 java 7 javax.json 中包含 add
方法.
Since there has been a lot of confusion about put
vs add
here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put
method and in java 7 javax.json contains the add
method.
在 Java 7 中使用构建器模式的示例如下所示:
An example of this using the builder pattern in java 7 looks something like this:
JsonObject jo = Json.createObjectBuilder()
.add("employees", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Doe")))
.build();
这篇关于如何使用 JSONObject 在 Java 中创建正确的 JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!