我正在读一个json字符串来映射' Map'变量
这是json:
"RootKey [name=Gil, department=]": {
"active": true,
"isPresent": true
}
这是变量:
private Map<String,Properties> map;
键是String:&#34; RootKey [name = Gil,department =]&#34; 该值将另存为对象&#39;属性&#39; 而&#39;属性&#39;是一个有2个变量的类:
public class Properties {
private String active;
private String isPresent;
}
问题是如何解析关键词&#39;所以我可以单独获得名称和部门吗?
谢谢!
答案 0 :(得分:0)
如果您的密钥格式始终相同,则可以在密钥内使用String的哑解析器。样本看起来像这样:(通过添加至少一些错误验证\错误处理随意改进)
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;
}
}
答案 1 :(得分:0)
一旦你获得了密钥(因为它是一个字符串),你可以使用一些正则表达式:
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/