Search code examples
javajsonjson-lib

Why can "class", "metaClass" and "declaringClass" not be used as keys in JSON-lib?


I stumbled about the effect, that the default configuration of JSON-lib (2.4) does not allow to use values with the keys class, metaClass and declaringClass (see JsonConfig.DEFAULT_EXCLUDES). Such key-value pairs are stripped from the JSON representation when the respective object is added to a JSONArray (please see my code snippet below).

// import net.sf.json.*;
JSONObject anElement = new JSONObject();
anElement.put("term", "a value");
anElement.put("class", "a value");

JSONArray theArray = new JSONArray();
theArray.add(anElement); // Default behavior.

boolean termWasAdded = (((JSONObject)theArray.get(0)).get("term")).equals("a value");
// evaluates to true
boolean classWasAdded = ((JSONObject)theArray.get(0)).get("class") != null;
// evaluates to false

My question: can anybody explain, why class, metaClass and declaringClass cannot be used as keys here? - Are these items somehow reserved symbols in JSON?


Solution

  • According to the source code:

    Exclude bean properties and/or map keys when serailizing to JSON (default=['class','metaClass','declaringClass'])

    Those are bean properties that you don't want to serialize when converting an object to JSON. Besides, there are methods that you can use to include those properties in the resulting JSON.