我有几个地图,其键是字符串,其值为Objects(Map<String, Object>
)。这些对象可以是其他地图,列表或文字值(类似于内存中的JSON表示)。例:
myMap = {
"users": [
{
"name": "Foo",
"surname": "Bar"
},
{
"name": "John",
"surname": "Doe"
}
]
}
我不想重新发明轮子,所以我想知道是否有一个Java库可以让我做这样的事情:
String secondUserSurname = (String) myMap.get("users[1].surname");
谢谢
编辑:为了澄清,我需要表达“users [1] .surname”是一个字符串。我将这个数据结构放在内存中,并将表达式放在.properties文件中。属性文件将告知在地图中访问哪个对象。这样我就可以快速更改对象以访问更改属性文件,而无需更改需要部署成本高昂的Java代码。
如果您有String
或bytes
可用的内容,那么您可以使用任何json
库将其反序列化为POJO
并获取字段。以下是Jackson的示例:
class UserObject {
private List<User> users;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
class User {
private String name;
private String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
驱动代码:
String content = "{" +
" \"users\": [" +
" {" +
" \"name\": \"Foo\"," +
" \"surname\": \"Bar\"" +
" }," +
" {" +
" \"name\": \"John\"," +
" \"surname\": \"Doe\"" +
" }" +
" ]" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
UserObject userObject = objectMapper.readValue(content, UserObject.class);
System.out.println(userObject.getUsers().get(0).getSurname());
允许我访问这些对象的库是JXPath,正如Gyro Gearless在评论中指出的那样,归功于他。