java 在java中将对象转换为Map<String, String>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30840456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:44:02  来源:igfitidea点击:

Convert object to Map<String, String> in java

javadictionary

提问by javaUser

Please suggest how to convert an Object to Map<String, String>in java. Tried org.apache.commons.beanutils.BeanMap(object). This is returning Map<String, Object only

请建议如何Map<String, String>在java中将对象转换为。试过 org.apache.commons.beanutils.BeanMap(object)。这是回来了Map<String, Object only

回答by Sharon Ben Asher

How about PropertyUtils.describe(object)though it works only for Java Beans (meaning Java Objects that implement getters)

PropertyUtils.describe(object)怎么样,虽然它只适用于 Java Beans(意思是实现 getter 的 Java 对象)

回答by Vikrant Kumar

I am assuming that you want to convert "Object[][] obj" to Map. In that case here is my solution:

我假设您想将“Object[][] obj”转换为 Map。在这种情况下,这是我的解决方案:

public static Map<String, String> convert2DArrayObjectToMap(Object[][] object)
{
    Map<String, String> map = new TreeMap<>();

    if (object != null)
    {
        for (int i = 0; i < object.length; i++)
        {
            if (object[i] != null)
            {
                for (int j = 0; j < object[i].length; j++)
                {
                    map.putAll((TreeMap<String, String>) object[i][j]);
                }
            }
        }
    }
    return map;
}

回答by Nagarz

Is there any reason for you not making it manually? It's not that much of a hassle, and you can implement it easily, something like this.

你有什么理由不手动制作吗?这不是那么麻烦,你可以很容易地实现它,就像这样。

HashMap<String, String> map = new HashMap<>();
//obj represents any object you wanna put inside the map
String key = "your key";
map.put(key, obj.toString());

if the object you want to turn into a map is an iterable object such as a list you can try something like this.

如果你想变成地图的对象是一个可迭代的对象,比如列表,你可以尝试这样的事情。

ArrayList<Object> list = new ArrayList<>();
HashMap<String, String> map = new HashMap<>();
Integer i = 0;
for (Object s:list) {
    map.put(String.valueOf(i), s.toString());
    i++;
}

回答by dly

Iterate over the Map<String, Object>and use newMap.put(key, value.toString());to fill a new Map<String, String>

迭代Map<String, Object>并用于newMap.put(key, value.toString());填充一个新的Map<String, String>