简体   繁体   中英

How to encode jsonArray when added to jsonobject before sending to server using httpsurlconnection

I am getting the contact list from android and I want to send it to the server using HTTP URL connection. But every time, the added array to the jsonobject at the end, show up in string double quotes. How do I encode jsonobject, when it has jsonArray inside?

     ArrayList<JSONObject> maps = new ArrayList<>();
     String result ="";
     try {

         for (int i = 0; i < contactDetails.size(); i++) {
             String FIRSTNAME =contactDetails.get(i).firstName;
             String LASTNAME =  contactDetails.get(i).lastName;
             String CONTACT = contactDetails.get(i).contactNumber;
             String EMAIL =  contactDetails.get(i).email;




            JSONObject contact = new JSONObject();

             contact.put("firstName",FIRSTNAME );
             contact.put("lastName",LASTNAME );
             contact.put("contactNumber",CONTACT );
             contact.put("email", EMAIL);

             maps.add(contact);
         }


     } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }
     JSONObject mainContact = new JSONObject();
     try {
         mainContact.put("token",token);
         mainContact.put("contact",maps.toString());
     } catch (JSONException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }


     return mainContact;
}  

You have to use GSON library to make it in a easy way

Something like this

ArrayList<String> mArrayList = new ArrayList<String>();
    mArrayList.add("First");
    mArrayList.add("Second");
    mArrayList.add("Third");
    mArrayList.add("Fourtrh");
    mArrayList.add("Fifth");
    mArrayList.add("Sixth");
    Log.i("Raw ArrayList", mArrayList);

    GsonBuilder gsonBuilder = new GsonBuilder();    
    Gson gson = gsonBuilder.create();

    String JSONObject = gson.toJson(mArrayList);
    Log.i("Converted JSONObject",JSONObject);

    Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
    String prettyJson = prettyGson.toJson(mArrayList);

    Log.i("Pretty JSONObject",prettyJson);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM