Exemple #1
0
  /**
   * Construct a JSONObject from a ResourceBundle.
   *
   * @param baseName The ResourceBundle base name.
   * @param locale The Locale to load the ResourceBundle for.
   * @throws JSONException If any JSONExceptions are detected.
   */
  public JSONObject(String baseName, Locale locale) throws JSONException {
    this();
    ResourceBundle bundle =
        ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader());

    // Iterate through the keys in the bundle.

    Enumeration keys = bundle.getKeys();
    while (keys.hasMoreElements()) {
      Object key = keys.nextElement();
      if (key instanceof String) {

        // Go through the path, ensuring that there is a nested JSONObject for each
        // segment except the last. Add the value using the last segment's name into
        // the deepest nested JSONObject.

        String[] path = ((String) key).split("\\.");
        int last = path.length - 1;
        JSONObject target = this;
        for (int i = 0; i < last; i += 1) {
          String segment = path[i];
          JSONObject nextTarget = target.optJSONObject(segment);
          if (nextTarget == null) {
            nextTarget = new JSONObject();
            target.put(segment, nextTarget);
          }
          target = nextTarget;
        }
        target.put(path[last], bundle.getString((String) key));
      }
    }
  }