将前端传递来的键值对转换成对象相应的值

得意犹堪夸世俗,诏黄新湿字如鸦。这篇文章主要讲述将前端传递来的键值对转换成对象相应的值相关的知识,希望能为你提供帮助。
功能说明比如前端网页传递过来的数据是id=123& name=zhangsan& age=23
通过工具类,最终能够将键值对赋给User对象

user{id:123,name:zhangsan,age:23}

实体类
@Data public class User { /** * 昵称 */ private String nickname; /** * 登录名 */ private String account; /** * 电话 */ private String tel; }

工具类
public class SearchConditionUtil { /** * 调用obj的set方法将searchCondition的值设置到obj中 * * @param obj * @param searchCondition 查询条件 * @param < T> */ public static < T> void initParam(T obj, SearchCondition searchCondition) { if (searchCondition != null) { String searchKey = searchCondition.getSearchKey(); String searchValue = https://www.songbingjia.com/android/searchCondition.getSearchValue(); if (searchKey != null & & searchKey.length() > 0 & & searchValue != null & & searchValue.length() > 0) { try { Method method = obj.getClass().getMethod("set" + StringUtil.firstLatterUpper(searchKey), String.class); method.invoke(obj, searchValue); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } } }

【将前端传递来的键值对转换成对象相应的值】SearchCondition是用来封装查询数据(key和value)的实体类,具体代码如下:
@Getter @Setter @ToString @Builder @AllArgsConstructor @NoArgsConstructor public class SearchCondition { /** * 条件查询的key */ private String searchKey; /** * 条件查询的value */ private String searchValue; }

测试代码
public static void main(String[] args) throws Exception { User user = new User(); String searchKey = "tel"; String searchValue = "https://www.songbingjia.com/android/432423"; SearchCondition searchCondition = new SearchCondition(searchKey, searchValue); initParam(user, searchCondition); System.out.println(user); }


    推荐阅读