如何将简单的JSONObject转换为java中的HashMap键值对

问题描述 投票:0回答:2

我有一个像这样的简单 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 结构无法更改。

java html json jstl
2个回答
1
投票

您可以尝试从字符串中删除所有

quotation
colons
commas
bracket
字符(或者用空格替换它们,以防您的字符串在单词之间没有空格,这样您就可以拆分后者)。同时删除子字符串
"table"

那么,你所拥有的就是

columns and descriptions
,使用
split
函数后,迭代会变得更容易。


0
投票
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

© www.soinside.com 2019 - 2024. All rights reserved.