Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object to map in java

Tags:

java

how I can convert Object to Map<String, String> where key is obj.parameter.name and value is obj.parameter.value

for exaple: Object obj = new myObject("Joe", "Doe"); convert to Map with keys: name, surname and values: Joe, Doe.

like image 357
Dmytro Svarychevskyi Avatar asked Sep 19 '18 12:09

Dmytro Svarychevskyi


People also ask

Can we convert object to map in Java?

In Java 8, we have the ability to convert an object to another type using a map() method of Stream object with a lambda expression. The map() method is an intermediate operation in a stream object, so we need a terminal method to complete the stream.

Can we convert object to map?

To convert an object to a Map , call the Object. entries() method to get an array of key-value pairs and pass the result to the Map() constructor, e.g. const map = new Map(Object. entries(obj)) .

How do you turn a POJO into a map?

A quick look at how to convert a POJO from/to a Map<K, V> with Jackson: // Create ObjectMapper instance ObjectMapper mapper = new ObjectMapper(); // Converting POJO to Map Map<String, Object> map = mapper. convertValue(foo, new TypeReference<Map<String, Object>>() {}); // Convert Map to POJO Foo anotherFoo = mapper.


1 Answers

Apart from the trick solution using reflection, you could also try jackson with one line as follows:

objectMapper.convertValue(o, Map.class);

A test case:

    @Test
    public void testConversion() {
        User user = new User();
        System.out.println(MapHelper.convertObject(user));
    }

    @Data
    static class User {
        String name = "Jack";
        boolean male = true;
    }


// output: you can have the right type normally
// {name=Jack, male=true}
like image 98
Hearen Avatar answered Oct 29 '22 17:10

Hearen