Last active
December 9, 2020 03:48
Java queryString to obj Example sample 两行代码(使用已有工具库)实现QueryString转对象,拒绝硬编码
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import lombok.Data; | |
import lombok.NonNull; | |
import lombok.extern.slf4j.Slf4j; | |
import org.apache.commons.beanutils.BeanUtils; | |
import org.apache.http.NameValuePair; | |
import org.apache.http.client.utils.URLEncodedUtils; | |
import org.junit.Test; | |
import java.nio.charset.StandardCharsets; | |
import java.util.List; | |
import static org.junit.Assert.assertEquals; | |
@Slf4j | |
public class Test4 { | |
@Data | |
public static class TestUser { | |
private String name; | |
private String name2; | |
} | |
@Test | |
public void test() { | |
String queryString = "name=haha&name2=xixi"; | |
List<NameValuePair> list = URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8); | |
TestUser testUser = new TestUser(); | |
setListToObj(testUser, list); | |
assertEquals(testUser.getName(), "haha"); | |
assertEquals(testUser.getName2(), "xixi"); | |
} | |
public static void setListToObj(@NonNull Object obj, @NonNull List<NameValuePair> list) { | |
for (NameValuePair nameValuePair : list) { | |
try { | |
BeanUtils.setProperty(obj, nameValuePair.getName(), nameValuePair.getValue()); | |
} catch (Exception ex) { | |
log.warn("listToObj 出错 nameValuePair NV:" + nameValuePair.getName() + "," + nameValuePair.getValue(), ex); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment