コード例 #1
0
  public static Bundle convertToBundle(JSONObject jsonObject) throws JSONException {
    Bundle bundle = new Bundle();
    @SuppressWarnings("unchecked")
    Iterator<String> jsonIterator = jsonObject.keys();
    while (jsonIterator.hasNext()) {
      String key = jsonIterator.next();
      Object value = jsonObject.get(key);
      if (value == null || value == JSONObject.NULL) {
        // Null is not supported.
        continue;
      }

      // Special case JSONObject as it's one way, on the return it would be Bundle.
      if (value instanceof JSONObject) {
        bundle.putBundle(key, convertToBundle((JSONObject) value));
        continue;
      }

      Setter setter = SETTERS.get(value.getClass());
      if (setter == null) {
        throw new IllegalArgumentException("Unsupported type: " + value.getClass());
      }
      setter.setOnBundle(bundle, key, value);
    }

    return bundle;
  }
コード例 #2
0
  public static JSONObject convertToJSON(Bundle bundle) throws JSONException {
    JSONObject json = new JSONObject();

    for (String key : bundle.keySet()) {
      Object value = bundle.get(key);
      if (value == null) {
        // Null is not supported.
        continue;
      }

      // Special case List<String> as getClass would not work, since List is an interface
      if (value instanceof List<?>) {
        JSONArray jsonArray = new JSONArray();
        @SuppressWarnings("unchecked")
        List<String> listValue = (List<String>) value;
        for (String stringValue : listValue) {
          jsonArray.put(stringValue);
        }
        json.put(key, jsonArray);
        continue;
      }

      // Special case Bundle as it's one way, on the return it will be JSONObject
      if (value instanceof Bundle) {
        json.put(key, convertToJSON((Bundle) value));
        continue;
      }

      Setter setter = SETTERS.get(value.getClass());
      if (setter == null) {
        throw new IllegalArgumentException("Unsupported type: " + value.getClass());
      }
      setter.setOnJSON(json, key, value);
    }

    return json;
  }