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.