为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

米脂 2019-10-06 14:47:18
我如何使用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字符串。
查看完整描述

3 回答

?
萧十郎

TA贡献1815条经验 获得超13个赞

可以编写小的可重用方法来创建人员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;

  }


查看完整回答
反对 回复 2019-10-06
  • 3 回答
  • 0 关注
  • 2323 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信