Search code examples
javajsonjson-simple

Problem with JSONValue


Am I totally missing something here? Why can't I get out what I'm putting in?

Set<String> stringSet = new LinkedHashSet<String>();
stringSet.add("firstName");
Map<String,Object> payload = new LinkedHashMap<String,Object>();
payload.put("properties", stringSet);

String sPayload = JSONValue.toJSONString(payload);
payload = (Map<String, Object>) JSONValue.parse(sPayload); // <-- payload == NULL

Solution

  • This is a json-simple bug (as of version 1.1) -- it doesn't know how to convert a Set into a JSON array, so it ends up just calling toString() on it and inserting the results verbatim.

    As a result, your JSON looks like:

    {"properties":[firstName]}
    

    Which causes JSONValue.parse() to choke on the unquoted firstName.

    If you use a List it works properly:

    {"properties":["firstName"]}
    

    There's an open issue about this problem: http://code.google.com/p/json-simple/issues/detail?id=23