獲取Java對象的所有字段值

問題

在對接第三方的請求接口時(shí),POST傳參要求的格式類似GET的params;
請求內(nèi)容類型,這里為 application/x-www-form-urlencoded
標(biāo)準(zhǔn)的編碼格式,數(shù)據(jù)被編碼為名稱/值對。
username=username&password=password&type=1&type=2

問題解析

  • 方法一: 將對象轉(zhuǎn)為List<NameValue>的list,用HttpPost請求類時(shí),可將list轉(zhuǎn)為JsonString放入entity. 具體方式請查看此例
  • 方法二: 將對象轉(zhuǎn)為 username=username&password=password&type=1&type=2 格式.在此方法中重寫了方法類的toString();
public String toString() {
String s = "";
  Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                s += field.getName()+"="+field.get(this).toString()+"&";
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
}

測試Demo如下

public class TestDemo {

    public static void main(String[] args) {
        Test test = new Test("zhangsan","123456","2");
        System.out.println("test.toString() = " + test.toString());
    }
    static class  Test{
        private String username;
        private String password;
        private String type;

        public Test(String username, String password, String type) {
            this.username = username;
            this.password = password;
            this.type = type;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        @Override
        public String toString() {
            String s = "";
            Field[] fields = this.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    s += field.getName()+"="+field.get(this).toString()+"&";
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            return s;
        }
    }
}

測試結(jié)果如下


測試結(jié)果
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容