private void getjson() {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject object_1 = new JSONObject();
JSONObject object_2 = new JSONObject();
JSONObject object_3 = new JSONObject();
try {
object_1.put("id", "3");
object_1.put("id1", "1");
object_1.put("id2", "2");
object_2.put("id3", "3");
object_2.put("id4", "4");
object_2.put("id5", "5");
object_3.put("id6", "6");
object_3.put("i7", "7");
object_3.put("id8", "9");
jsonArray.put(object_1);
jsonArray.put(object_2);
jsonArray.put(object_3);
jsonObject.put("la", jsonArray);
jsonObject.put("qita", "5666666");
} catch (JSONException e) {
e.printStackTrace();
} Log.e("自定义的json", jsonObject.toString());
}
打印结果为:
自定义的json: {"la":[{"id2":"2","id":"3","id1":"1"},{"id5":"5","id4":"4","id3":"3"},{"id6":"6","i7":"7","id8":"9"}],"qita":"5666666"}
ArrayList<AddPersonMessageBean> arrayList = new ArrayList<AddPersonMessageBean>();
private void changeJson() throws JSONException {
AddPersonMessageBean d = new AddPersonMessageBean();
d.setName("dhjshds");
d.setPhone_num("hdsdhshd");
arrayList.add(d);
JSONArray array=new JSONArray();
for(AddPersonMessageBean bean:arrayList){
array.put(new JSONObject(beanToMap(bean)));
}
JSONObject jsonObject=new JSONObject();
jsonObject.put("bean",array);
Log.e(TAG, "changeJson: "+jsonObject.toString());
}
public <T> Map<String, Object> beanToMap(T t){
Field[] fields = t.getClass().getDeclaredFields();
Method[] methods = t.getClass().getMethods();
Map<String, Object> map = new HashMap<String, Object>();
for(Field field : fields){
for(Method method : methods){
if(method.getName().startsWith("get") && method.getName().toLowerCase().indexOf(field.getName().toLowerCase()) >= 0){
try {
map.put(field.getName(), method.invoke(t, new Object[]{}));
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
return map;
}
E/打印结果: changeJson: {"bean":[{"contactNum":null,"phone_num":"hdsdhshd","relative":null,"name":"dhjshds"}]}