将对象放入数组中

要求最终返回的格式是这样的:

{
"UserKey":"5e8d679c6dba993af8bf3e0c",
"ExternalUsers":
 [ {
  "ExternalUserId":"test15",
  "ExternalPassword":"123456"
 } ]
}

代码实现:

Map<String,Object> result=new HashMap<>();

    JSONObject json = new JSONObject();

    json.put("ExternalUserId", user.getAccount());
    json.put("ExternalPassword", user.getPassword());
    
     JSONArray array= new JSONArray();
     array.add(json);
     
     result.put("userKey",uId);
     result.put("externalUsers",array);
   JSONObject authorizeModelUser = modelUserHelper.authorizeExternalUser(result,modelUri);

如果数组里是多个对象的话,那就创建多个JSONObject,json1.put()放不同的值,再利用

    @Test
    public void testJsonObj() throws Exception {
        JSONObject jsonObj = new JSONObject();
        Student student_0 = new Student("jarworker", 18, "男");
        jsonObj.put("success", "123");
        jsonObj.put("student", student_0);
        System.out.println("添加对象到json对象:" + jsonObj.toJSONString());
        System.out.println("===============================================");
        JSONArray jsonArr = new JSONArray();
        Student student_1 = new Student("静香", 12, "女");
        Student student_2 = new Student("大熊", 13, "男");
        jsonArr.add(student_0);
        jsonArr.add(student_1);
        jsonArr.add(student_2);
        jsonObj.put("studentArr", jsonArr);
        System.out.println("添加对象到json数组:" + jsonObj.toJSONString());
        System.out.println("===============================================");
        System.out.println("对象中key为student的对象的name值为:" +                 jsonObj.getJSONObject("student").getString("name"));
    }

     array.add(json1)将对象放入数组里

参考:https://www.jianshu.com/p/31091b137453

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页