Vignesh Paramasivam Vignesh Paramasivam - 2 months ago 8
Java Question

Converting two arrays into json string object using java

I have two arrays,

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


How do i convert it into below json structure, where it should start with '
[
' and end with '
]
',

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

Answer
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 );
}

and guess you want this to send it to server in your required format then convert jsonarray into String

String data = arr.toString();
Comments