Reputation: 1474
i have a problem with BeanUtils, i need to convert Map to POJO with different property names
entity:
public class User {
private int id;
private String nickname;
private int agility;
public int getId() {
return id;
}
// getters and setters
}
Target application API returns HashMap (via XML-RPC) with something like that:
user_id => "123456"
nickname => "Bob"
agility => 30
but my POJO class doesn't have user_id
property
how to translate property name user_id
=> id
?
i didn't find any annotations for that case
Upvotes: 1
Views: 3940
Reputation: 1474
BeanUtils is not suitable for my case, i used Gson library. Gson has feature - convert object to json. After that i convert json into User
class. name
property marked by annotation @SerializedName
entity class:
class User {
@SerializedName("user_id")
private int id;
private String name;
// getters and setters here
// .toString
}
usage:
Map<String,String> apiObject = new HashMap<>();
apiObject.put("user_id","123123");
apiObject.put("name","Bob");
Gson gson = new Gson();
String json = gson.toJson(values);
User user = gson.fromJson(json, User.class);
System.out.println(user);
example output:
User{id=123123, name='Bob'}
Upvotes: 1
Reputation: 1906
If it is permitted to later the HashMap after you received it, you change change the key.
map.put("id", map.remove("user_id"));
Then use BeanUtils to populate your bean:
User usr = new User();
BeanUtils.populate(usr, map);
Upvotes: 1