0

I faced this problem recently in production where I will be storing my HashMap value as JSON and the code would like

import java.util.*;
import org.json.JSONObject;
public class JSONParser {
    public static void main(String[] args) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("1", "a");
        map.put("2", "b");
        System.out.println("Map contains : "+ map.toString());      
        JSONObject json = new JSONObject(map.toString());
        System.out.println("Json contains :: "+json);
    }
}

And it was working fine producing the expected output as

Map contains : {2=b, 1=a}

Json contains :: {2:b, 1:a}

After bundling with the latest org.json.jar it throws exception like the following

org.json.JSONException: Expected a ':' after a key at 3 [character 4 line 1]

So, to overcome this I have modified my code with

private String convertToJSONString(Map<String, Object> hm) throws Exception {

     Set<String> keys = hm.keySet();
     JSONObject json = new JSONObject();
     for(String key : keys) {
         Object value = hm.get(key);
         json.put(key, value);
     }
     return json.toString();
}

I have attached the source code link of older json version and new json version

Just curious to know why they removed such nice parsing? Since I am doing some additional workaround now.

PS: I am not sure weather I can discuss about this here since it is not related to debugging or general programming. But still posting it here because many would be using this library and wouldn't aware of this recent change.

If you find the post as useless/inappropriate one please let me know with comments I'll remove the post.

Tom Taylor
  • 3,344
  • 2
  • 38
  • 63
  • Your not creating your `JSONObject` correctly. `{2=b, 1=a}` is not valid json, see http://stackoverflow.com/questions/12155800/how-to-convert-hashmap-to-json-object-in-java – ug_ Dec 03 '16 at 15:39
  • Yes you are right ! _ug Then why it worked with old json but not with the new one :-( – Tom Taylor Dec 03 '16 at 15:43

0 Answers0