Well, you can achieve that with Jackson, too. (and it seems to be more comfortable since you were considering using jackson).
Use ObjectMapper's convertValue method:
final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);
No need to convert into JSON string or something else; direct conversion does much faster.
Answer from Jongwook Choi on Stack OverflowWell, you can achieve that with Jackson, too. (and it seems to be more comfortable since you were considering using jackson).
Use ObjectMapper's convertValue method:
final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);
No need to convert into JSON string or something else; direct conversion does much faster.
A solution with Gson:
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(map);
MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class);
You can convert Map to JSON using Jackson as follows:
Map<String,String> payload = new HashMap<>();
payload.put("key1","value1");
payload.put("key2","value2");
String json = new ObjectMapper().writeValueAsString(payload);
System.out.println(json);
Using jackson, you can do it as follows:
ObjectMapper mapper = new ObjectMapper();
String clientFilterJson = "";
try {
clientFilterJson = mapper.writeValueAsString(filterSaveModel);
} catch (IOException e) {
e.printStackTrace();
}
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}
This is how you'd do it:
import java.util.Map;
import java.util.HashMap;
import java.util.Map.Entry;
import java.lang.reflect.Field;
public class Main {
public int a = 3;
public String b = "Hello";
public static void main(String[] args) {
Map<String, Object> map = parameters(new Main());
for (Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
public static Map<String, Object> parameters(Object obj) {
Map<String, Object> map = new HashMap<>();
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
try { map.put(field.getName(), field.get(obj)); } catch (Exception e) { }
}
return map;
}
}
Basically, you use reflection to get all of the fields in the class. Then, you access all of those fields of the object. Keep in mind that this only works for fields accessible from the method that gets the fields.