猿问

在java中将对象转换为映射

我如何将 Object 转换为Map<String, String> where keyis obj.parameter.nameand valueisobj.parameter.value

例如:Object obj = new myObject("Joe", "Doe");转换为Map键:名称,姓氏和值:Joe,Doe。


MM们
浏览 179回答 2
2回答

不负相思意

除了使用反射的技巧解决方案外,您还可以尝试jackson如下一行:objectMapper.convertValue(o, Map.class);一个测试用例:&nbsp; &nbsp; @Test&nbsp; &nbsp; public void testConversion() {&nbsp; &nbsp; &nbsp; &nbsp; User user = new User();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(MapHelper.convertObject(user));&nbsp; &nbsp; }&nbsp; &nbsp; @Data&nbsp; &nbsp; static class User {&nbsp; &nbsp; &nbsp; &nbsp; String name = "Jack";&nbsp; &nbsp; &nbsp; &nbsp; boolean male = true;&nbsp; &nbsp; }// output: you can have the right type normally// {name=Jack, male=true}

拉丁的传说

这是你的做法:import java.util.Map;import java.util.HashMap;import java.util.Map.Entry;import java.lang.reflect.Field;public class Main {&nbsp; &nbsp; public int a = 3;&nbsp; &nbsp; public String b = "Hello";&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Map<String, Object> map = parameters(new Main());&nbsp; &nbsp; &nbsp; &nbsp; for (Entry<String, Object> entry : map.entrySet()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(entry.getKey() + ": " + entry.getValue());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static Map<String, Object> parameters(Object obj) {&nbsp; &nbsp; &nbsp; &nbsp; Map<String, Object> map = new HashMap<>();&nbsp; &nbsp; &nbsp; &nbsp; for (Field field : obj.getClass().getDeclaredFields()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; field.setAccessible(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try { map.put(field.getName(), field.get(obj)); } catch (Exception e) { }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return map;&nbsp; &nbsp; }}基本上,您使用反射来获取类中的所有字段。然后,您访问对象的所有这些字段。请记住,这仅适用于可从获取字段的方法访问的字段。
随时随地看视频慕课网APP

相关分类

Java
我要回答