Sid Sid - 1 year ago 97
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;


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;

protected void onCreate(Bundle savedInstanceState) {

invitationArrayList = new ArrayList<>();

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


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


// 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 Source

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:,%20V)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download