Java 映射变量 --> 将键解析为对象
Java Map variable --> parse the Key to an Object
我正在读取 json 字符串到 'Map' 变量。
这是 json :
"RootKey [name=Gil, department=]": {
"active": true,
"isPresent": true
}
这是变量:
private Map<String,Properties> map;
关键是字符串:"RootKey [name=Gil, department=]"
该值被保存为对象 'Properties'
而 'Properties' 是一个 class,它有 2 个变量:
public class Properties {
private String active;
private String isPresent;
}
问题是如何解析 'key' 这样我就能分别得到姓名和部门?
谢谢!
如果您的键格式始终相同,您可以使用键内字符串的哑解析器。示例如下所示:(可以通过至少添加一些错误验证\错误处理来随意改进)
public static void main(String args[]) {
String test = "RootKey [name=Gil, department=]";
KeyInfo cls = getKey(test);
System.out.println(cls.name + " " + cls.department);
}
private static KeyInfo getKey(String jsonKey) {
// parse the content between brackets
String[] tokens = jsonKey.substring(jsonKey.indexOf('[')+1, jsonKey.indexOf(']')).split(", ");
// build your key info
return new KeyInfo(tokens[0].substring(tokens[0].indexOf('=') + 1),
tokens[1].substring(tokens[1].indexOf('=') + 1));
}
private static class KeyInfo {
private final String name;
private final String department;
private KeyInfo(String name, String department) {
this.name = name;
this.department = department;
}
}
您可以在检索到密钥后使用一些正则表达式(因为它是一个字符串):
Pattern p = Pattern.compile(".*? \[name=(.*?), department=(.*?)\]");
Matcher m = p.matcher(yourKey);
if (m.find()) {
System.out.println(m.group(1)); // contains the name
System.out.println(m.group(2)); // contains the departement
}
如果您从未听说过正则表达式(对此我表示怀疑)或不理解我的正则表达式,请尝试使用此在线正则表达式测试器:https://regex101.com/
我正在读取 json 字符串到 'Map' 变量。
这是 json :
"RootKey [name=Gil, department=]": {
"active": true,
"isPresent": true
}
这是变量:
private Map<String,Properties> map;
关键是字符串:"RootKey [name=Gil, department=]" 该值被保存为对象 'Properties' 而 'Properties' 是一个 class,它有 2 个变量:
public class Properties {
private String active;
private String isPresent;
}
问题是如何解析 'key' 这样我就能分别得到姓名和部门?
谢谢!
如果您的键格式始终相同,您可以使用键内字符串的哑解析器。示例如下所示:(可以通过至少添加一些错误验证\错误处理来随意改进)
public static void main(String args[]) {
String test = "RootKey [name=Gil, department=]";
KeyInfo cls = getKey(test);
System.out.println(cls.name + " " + cls.department);
}
private static KeyInfo getKey(String jsonKey) {
// parse the content between brackets
String[] tokens = jsonKey.substring(jsonKey.indexOf('[')+1, jsonKey.indexOf(']')).split(", ");
// build your key info
return new KeyInfo(tokens[0].substring(tokens[0].indexOf('=') + 1),
tokens[1].substring(tokens[1].indexOf('=') + 1));
}
private static class KeyInfo {
private final String name;
private final String department;
private KeyInfo(String name, String department) {
this.name = name;
this.department = department;
}
}
您可以在检索到密钥后使用一些正则表达式(因为它是一个字符串):
Pattern p = Pattern.compile(".*? \[name=(.*?), department=(.*?)\]");
Matcher m = p.matcher(yourKey);
if (m.find()) {
System.out.println(m.group(1)); // contains the name
System.out.println(m.group(2)); // contains the departement
}
如果您从未听说过正则表达式(对此我表示怀疑)或不理解我的正则表达式,请尝试使用此在线正则表达式测试器:https://regex101.com/