如何使用JSONObject在Java中创建正确的JSONArray

我如何使用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字符串。


米脂
浏览 2324回答 3
3回答

萧十郎

可以编写小的可重用方法来创建人员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();    response.put("employees", employees );    response.put("manager", managers );    return response;  }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java