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.
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.
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)) .
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With