Using Json-lib with JRuby

Since version 2.0 Json-lib has integrated JRuby support, meaning that you can take advantge of the library's Java and XML support. There are other features as well:

  • JSONObject supports the leftShift (<<) operator to append values, the following rules apply:
    • If the shifted arg is a Map, it will call putAll() on the object.
    • If the shifted arg is a List and its size == 2, the first element will be the key, and the second will be the value.
    • If the shifted arg is a List and its size > 2, the first element will be the key, the arg will be shifted by 1 and passed as the value (will create a JSONArray because it is a List).
    • Any other type will be discarded, the object will not be affected nor an exception will be thrown.
  • JSONObject and JSONarray implement java.util.Comparable, which enables the use of the comparison operators with them.
  • JSONObject implements java.util.Map and JSONArray implements java.util.List, anything you can do with Maps and List can be done with JSONObject and JSONArray.
  • JSONObject.empty? and JSONArray.empty? provide rubylicious shortcuts to isEmpty().