Android 自定义Gson格式

 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"}]}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值