简体   繁体   中英

How to convert a simple JSONObject into HashMap Key,Value pairs in java

I have a simple JSON object like this:

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

What I need to do is create a HashMap or Map to generate this HTML using a forEach with JSTL:

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

JSON STRUCTURE CANNOT CHANGE.

You could try to remove all quotation , colons , commas and bracket chars from the string (or replace them with spaces, in case your string don't have spaces between the words, so you can split latter). Also remove the substring "table" .

Then, all you'll have is columns and descriptions , it becomes easier to iterate after used the split function.

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());
        }

If you want to keep the keys sorted, you might consider using TreeMap instead of HashMap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM