How to raise an object on java.util.Map?

I have an object in my code of type Object: Object o

Instance class: Object: o.getClass()provides Object.

Now it should be a card! How can I convert this to a map?

I tried: Map<String, Object> map = (HashMap<String,Object>)o

But this returns: java.lang.ClassCastException: [Ljava.lang.Object; cannot be added to java.util.HashMap

Instance "o" comes from an XMLRPC request. This query incorrectly qualifies variables

Please take a look at this!

EDIT:

Now I have the following problem: o.getClass().getName()gives java.util.ArrayList,

o.get(0)It gives [Ljava.lang.Object;@739e8329,

and o.get(0).getClass().getName()gives java.lang.String.

I can’t find out what to do.

EDIT2:

Finally I found out what happened. The software that created this object smoothed the data structure into String (valueOf ()). So, when I printed the variable, it returned [Ljava.util.Object, which was actually a string containing this information.

Thanks guys!

+4
source share
4 answers

[Ljava.lang.Objectindicates the type of object o - this is an array of objects - this Object[]. You cannot direct him to Map.

You may find it helpful if you look at: java: what is it: [Ljava.lang.Object ;?

You stated that it was .getClass()indicated Object, but was it Objector [LObject? Compare with:

    Object[] array= new Object[]{};
    Object simple = new Object();

    System.out.println(array.getClass());
    System.out.println(simple.getClass());      

which prints:

class [Ljava.lang.Object;
class java.lang.Object
+8
source

, o Map. Map.

. , . , :

 Object[] objects = (Object[]) o;
 if (objects != null && objects.length > 0) {
    Object object = objects[0];
    if (object instanceof Map) {
      Map map = (Map) object;
      System.out.println("Heureka!");
    }
 }
+7

You cannot use oin Mapbecause it does not implement an interface Map. The exception shows that it ois an array of Objects.

+1
source
ObjectMapper oMapper = new ObjectMapper();
    Map<String, String> map = oMapper.convertValue(YOUROBJECT, Map.class);
    List<InputValues> inputValuesList = new ArrayList<InputValues>();
   for(String key : map.keySet()){
        inputValuesList.add(new InputValues(key,map.get(key).toString()) );
    }


    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.9</version>
    </dependency>

The InputValues ​​class has 2 rows. You also need to add Jackson's addiction.

0
source

Source: https://habr.com/ru/post/1763568/


All Articles