使用java将两个数组转换为json字符串对象

时间:2016-09-27 12:22:37

标签: java arrays json

我有两个数组,

id = [1,2,3]
pass = [a,b,c]

如何将其转换为以下json结构,其中应以“[”开头,以“]”结尾,

  [
    { 
       "user": "1", 
       "password": "a"
    },
   { 
       "user": "1", 
       "password": "a"
    },
   { 
       "user": "1", 
       "password": "a"
    }
   ]

1 个答案:

答案 0 :(得分:3)

JSONArray arr = new JSONArray();
JSONObject obj;
for( int i = 0; i < yourUserArr.length; i++ ){
  obj = new JSONObject();
  obj.put("user", yourUserArr[i]);
  obj.put("password", yourPassArr[i]);
  arr.put( obj );
}

并猜测您希望将其以所需格式发送到服务器,然后将jsonarray转换为String

String data = arr.toString();