问题
如何使用JSONObject在Java中创建如下所示的JSON对象?
{
"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字符串。
#1 热门回答(209 赞)
以下是使用java 6开始的一些代码:
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
vsadd
的混淆,我将尝试解释其中的差异。在java 6org.json.JSONArray中包含put
方法,在java 7javax.json中包含add
方法。
使用java 7中的构建器模式的示例如下所示:
JsonObject jo = Json.createObjectBuilder()
.add("employees", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Doe")))
.build();
#2 热门回答(11 赞)
我想你是从服务器或文件中获取这个JSON,并且你想从中创建一个JSONArray对象。
String strJSON = ""; // your string goes here
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();
// once you get the array, you may check items like
JSONOBject jObject = jArray.getJSONObject(0);
希望这可以帮助 :)
#3 热门回答(2 赞)
Small可重用的方法可以写成用于创建人json对象以避免重复代码
JSONObject getPerson(String firstName, String lastName){
JSONObject person = new JSONObject();
person .put("firstName", firstName);
person .put("lastName", lastName);
return person ;
}
public JSONObject getJsonResponse(){
JSONArray employees = new JSONArray();
employees.put(getPerson("John","Doe"));
employees.put(getPerson("Anna","Smith"));
employees.put(getPerson("Peter","Jones"));
JSONArray managers = new JSONArray();
managers.put(getPerson("John","Doe"));
managers.put(getPerson("Anna","Smith"));
managers.put(getPerson("Peter","Jones"));
JSONObject response= new JSONObject();
person .put("employees", employees );
person .put("manager", managers );
return response;
}