我正在从android获取联系人列表,我想使用HTTP URL连接将其发送到服务器。但是每次,最后添加到jsonobject的数组都会以字符串双引号显示。内部包含jsonArray时,如何编码jsonobject?
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;
}
答案 0 :(得分:0)
您必须使用GSON库才能轻松实现它
类似这样的东西
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);