【问题标题】:How to convert a simple JSONObject into HashMap Key,Value pairs in java如何将简单的 JSONObject 转换为 Java 中的 HashMap 键、值对
【发布时间】:2016-03-10 00:12:39
【问题描述】:

我有一个像这样的简单 JSON 对象:

 String jsonString = new String( "{ 
    "table": { "column1" : "description1", 
"column2" : "description2", 
"columnN" : "descriptionN" } }" );

我需要做的是使用带有 JSTL 的 forEach 创建一个 HashMap 或 Map 来生成这个 HTML:

    <table>
    <tr>
    <td id="column1">description1</td>
    <td id="column2">description2</td>
    <td id="columnN">descriptionN</td>
    </tr>
...
    </table>

JSON 结构无法更改。

【问题讨论】:

  • 使用 JSON 库怎么样?
  • 字符串操作应该怎么做?
  • 是的,这就是想法,但如何?我正在尝试迭代“表”,但我不知道该怎么做?

标签: java json html jstl core


【解决方案1】:

您可以尝试从字符串中删除所有 quotationcolonscommasbracket 字符(或者用空格替换它们,以防您的字符串在单词之间没有空格,所以您可以拆分后者)。同时删除子字符串"table"

那么,你就只有columns and descriptions了,使用split函数后迭代变得更容易了。

【讨论】:

    【解决方案2】:
    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

    【讨论】:

      猜你喜欢
      • 2013-12-02
      • 2020-06-11
      • 2019-02-03
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      相关资源
      最近更新 更多