我有一个像这样的简单 JSON 对象:
String jsonString = new String( "{
"table": { "column1" : "description1",
"column2" : "description2",
"columnN" : "descriptionN" } }" );
我需要做的是创建一个 HashMap 或 Map 来使用 forEach 和 JSTL 生成此 HTML:
<table>
<tr>
<td id="column1">description1</td>
<td id="column2">description2</td>
<td id="columnN">descriptionN</td>
</tr>
...
</table>
JSON 结构无法更改。
您可以尝试从字符串中删除所有
quotation
、colons
、commas
和 bracket
字符(或者用空格替换它们,以防您的字符串在单词之间没有空格,这样您就可以拆分后者)。同时删除子字符串 "table"
。
那么,你所拥有的就是
columns and descriptions
,使用split
函数后,迭代会变得更容易。
String json = new String( "{ \"table\": { \"column1\" : \"description1\", \"column2\" : \"description2\", \"columnN\" : \"descriptionN\" } }" );
json = json.replace("{", "")
.replace("}", "")
.replace("\"", "")
.replace("table:", "");
HashMap<String, String> map = new HashMap<String, String>();
String[] elems = json.split(",");
for (String string : elems) {
String[] keyval = string.split(":");
map.put(keyval[0].trim(), keyval[0].trim());
}
//Printing the map
for (Entry<String, String> kv : map.entrySet()) {
System.out.println(kv.getKey() + " : " + kv.getValue());
}
如果你想保持键的排序,你可以考虑使用TreeMap而不是HashMap