我正在使用Java和Regex解析一个配置文件。
在此之后,我得到以下格式的字符串ArrayList。
我想从上面的示例获得有效的JSON:
{
"ssid": "test1",
"psk": "154695",
"key_mgmt": "WPA-PSK",
"sim_slot": "-1",
"imsi": "none",
"priority": 1
}
我怎么能以任何简单的方式做到这一点?任何图书馆? (我不能是JSON我可以接受任何其他格式(XML,CSV等))
修改
我尝试通过推荐更新正则表达式:
while (m.find()) {
String foundOccurence = m.group();
foundOccurence = foundOccurence.replace("=",":");
foundOccurence = foundOccurence.replaceAll("\\s*([^:]+):(.*(\\n|$))","\"$1\":$2");
allMatches.add(foundOccurence);
}
但结果仍然无效(但几乎是),见下图:
答案 0 :(得分:0)
有点难以理解你真正想要的东西。
从此输入字符串:
{ ssid:"test1" psk:"test154695" key_mgmt:WPA-PSK sim_slot:"-1" imsi:"none" priority:1 }
似乎你想得到这个输出字符串:
{ "ssid": "test1", "psk": "test154695", "key_mgmt": "WPA-PSK", "sim_slot": "-1", "imsi": "none", "priority": 1 }
我看到的差异:
key_mgmt
的值附近添加双引号,将WPA-PSK
转为"WPA-PSK"
:
这是一个实现这一点,并验证。 我希望这是你要找的东西, 或基于此,你将能够弄明白。
String malformed = "{\n" +
" ssid:\"test1\"\n" +
" psk:\"test154695\"\n" +
" key_mgmt:WPA-PSK\n" +
" sim_slot:\"-1\"\n" +
" imsi:\"none\"\n" +
" priority:1\n" +
"}";
String expected = "{\n" +
" \"ssid\": \"test1\",\n" +
" \"psk\": \"test154695\",\n" +
" \"key_mgmt\": \"WPA-PSK\",\n" +
" \"sim_slot\": \"-1\",\n" +
" \"imsi\": \"none\",\n" +
" \"priority\": 1\n" +
"}";
Pattern p = Pattern.compile("(\\w+):([^\\n]*)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(malformed);
StringBuilder builder = new StringBuilder("{\n");
while (m.find()) {
String key = m.group(1);
String value = m.group(2);
if (key.equals("key_mgmt")) {
value = "\"" + value + "\"";
}
builder.append(String.format(" \"%s\": %s,\n", key, value));
}
builder.replace(builder.length() - 2, builder.length(), "\n}");
String corrected = builder.toString();
assert expected.equals(corrected);