Sid Sid - 2 months ago 8
Java Question

Convert string to json object gives an error

I have to send the json array to web server. I have created json array from array list. I have a helper class which sends json object to server.

So I want to convert the json array to json object.

I tried to do this:

Async Task:

public class SendMultipleInvitesAsyncTask extends AsyncTask<String, Void, JSONObject> {

private Context context;
JSONArray array = new JSONArray();

public SendMultipleInvitesAsyncTask(Context context)
{

this.context = context;

}

@Override
protected JSONObject doInBackground(String... params) {
try {
String api = context.getResources().getString(R.string.server_url) + "contactsapi/sendMultipleInvite.php";

JSONObject obj = new JSONObject(params[0]);

ServerRequest request = new ServerRequest(api,obj);
return request.sendRequest();

} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
}


Activity :

public class SendMultipleInvites extends AppCompatActivity {

private ArrayList<Invitation> invitationArrayList;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_multiple_invites);

invitationArrayList = new ArrayList<>();

Invitation invitation = new Invitation("3","17/02/2016","55165122","1","user10");

invitationArrayList.add(invitation);

invitation = new Invitation("3","17/02/2016","282751221","1","user10");

invitationArrayList.add(invitation);

// JSONArray jsArray = new JSONArray(invitationArrayList);


Gson gson=new Gson();
String toServer=gson.toJson(invitationArrayList);



new SendMultipleInvitesAsyncTask(SendMultipleInvites.this).execute(toServer);


But this gives me an error that json object can not be converted to json array.

I want to send input of json array like this:

{
"invitations": [
{

"sender_id" : 3,
"date" : "12/08/2016",
"invitee_no" : "196756456",
"status" : "1",
"user_name" : "user10"

},
{

"sender_id" : 3,
"date" : "12/08/2016",
"invitee_no" : "13633469",
"status" : "1",
"user_name" : "user9"

}
]

}


How can I do this? How to pass it through an async task. Or what is going wrong here? Please help Thank you..

Answer

invitationArrayList is your ArrayList so jo get a JSON array. If you want to wrap this array in a JSON object you have to this in java as well.

For example:

String toServer = gson.toJson(
    Collections.singletonMap("invitations", invitationArrayList)
);

(assumed that gson.toJson works as expected. I'm no gson expert because I'm mostly use jackson...)

JavaDoc for Collections.singletonMap: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#singletonMap(K,%20V)