0

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"
    }
   ]
Vignesh Paramasivam
  • 2,360
  • 5
  • 26
  • 57
  • 2
    What did you try so far? – baao Sep 27 '16 at 12:28
  • 2
    Possible duplicate of [Converting Java objects to JSON with Jackson](http://stackoverflow.com/questions/15786129/converting-java-objects-to-json-with-jackson) – Prabhat Sep 27 '16 at 12:28
  • @baao I mapped the two tables and converted into json, but that i can get something like this, {"user":["1","2","3"],","password":["a","b","c"]}. But i am not able to merge it like i wanted, also it is not covered with square brackets(array format) – Vignesh Paramasivam Sep 27 '16 at 12:33
  • @VigneshParamasivam i guess you want 1:a ,2:b and 3:c mapping but your example can also be achieved easily with little manipulation with array indexes , let me know if you want the exact – Pavneet_Singh Sep 27 '16 at 12:40

1 Answers1

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

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

String data = arr.toString();
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68