Java Code Examples for org.json.JSONObject#NULL

The following examples show how to use org.json.JSONObject#NULL . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonConverter.java    From Leanplum-Android-SDK with Apache License 2.0 7 votes vote down vote up
public static JSONArray listToJsonArray(Iterable<?> list) throws JSONException {
  if (list == null) {
    return null;
  }
  JSONArray obj = new JSONArray();
  for (Object value : list) {
    if (value instanceof Map) {
      Map<String, ?> mappedValue = CollectionUtil.uncheckedCast(value);
      value = mapToJsonObject(mappedValue);
    } else if (value instanceof Iterable) {
      value = listToJsonArray((Iterable<?>) value);
    } else if (value == null) {
      value = JSONObject.NULL;
    }
    obj.put(value);
  }
  return obj;
}
 
Example 2
Source File: ObjectMapper.java    From Dream-Catcher with MIT License 6 votes vote down vote up
private JSONObject _convertToJSONObject(Object fromValue)
    throws JSONException, InvocationTargetException, IllegalAccessException {
  JSONObject jsonObject = new JSONObject();
  Field[] fields = fromValue.getClass().getFields();
  for (int i = 0; i < fields.length; ++i) {
    JsonProperty property = fields[i].getAnnotation(JsonProperty.class);
    if (property != null) {
      // AutoBox here ...
      Object value = fields[i].get(fromValue);
      Class clazz = fields[i].getType();
      if (value != null) {
        clazz = value.getClass();
      }
      String name = fields[i].getName();
      if (property.required() && value == null) {
        value = JSONObject.NULL;
      } else if (value == JSONObject.NULL) {
        // Leave it as null in this case.
      } else {
        value = getJsonValue(value, clazz, fields[i]);
      }
      jsonObject.put(name, value);
    }
  }
  return jsonObject;
}
 
Example 3
Source File: JavaSystemProperty.java    From androiddevice.info with GNU General Public License v2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public Object getProperty() {
    if(Build.VERSION.SDK_INT < 9) {
        return JSONObject.NULL;
    }
    JSONObject jsonObject = new JSONObject();
    Properties properties = System.getProperties();
    for (String propertyName : properties.stringPropertyNames()) {
        try {
            jsonObject.put(propertyName, properties.getProperty(propertyName));
        } catch (JSONException e) {
        }
    }
    return jsonObject;
}
 
Example 4
Source File: ApiWeb3Aion.java    From aion with MIT License 6 votes vote down vote up
public RpcMsg ops_getBlockDetailsByHash(Object _params){
    String _blockHash;
    if (_params instanceof JSONArray) {
        _blockHash = ((JSONArray) _params).get(0) + "";
    } else if (_params instanceof JSONObject) {
        _blockHash = ((JSONObject) _params).get("block") + "";
    } else {
        return new RpcMsg(null, RpcError.INVALID_PARAMS, "Invalid parameters");
    }

    Block block = this.ac.getBlockchain().getBlockByHash(ByteUtil.hexStringToBytes(_blockHash));

    if (block == null) {
            return new RpcMsg(JSONObject.NULL);
    }

    Block mainBlock = this.ac.getBlockchain().getBlockByNumber(block.getNumber());

    if (mainBlock == null || !Arrays.equals(block.getHash(), mainBlock.getHash())) {
        return new RpcMsg(JSONObject.NULL);
    }

    return rpcBlockDetailsFromBlock(block);
}
 
Example 5
Source File: JSONPropertyTest.java    From squidb with Apache License 2.0 6 votes vote down vote up
private <T> T deserializeObject(Object object, Type type) throws JSONException {
    if (JSONObject.NULL == object) {
        return null;
    }
    if (!(object instanceof JSONObject)) {
        return (T) object;
    }
    JSONObject jsonObject = (JSONObject) object;
    if (JSONPojo.class.equals(type)) {
        JSONPojo result = new JSONPojo();
        result.pojoInt = jsonObject.getInt("pojoInt");
        result.pojoDouble = jsonObject.getDouble("pojoDouble");
        result.pojoStr = jsonObject.getString("pojoStr");
        result.pojoList = deserializeArray(jsonObject.getJSONArray("pojoList"), Integer.class);
        return (T) result;
    } else if (type instanceof ParameterizedType && Map.class
            .equals(((ParameterizedType) type).getRawType())) {
        return (T) deserializeMap(jsonObject, ((ParameterizedType) type).getActualTypeArguments()[1]);
    }
    throw new JSONException("Unable to parse object " + object);
}
 
Example 6
Source File: ApiWeb3Aion.java    From aion with MIT License 6 votes vote down vote up
public RpcMsg priv_dumpBlockByNumber(Object _params) {
    String numberString;
    if (_params instanceof JSONArray) {
        numberString = ((JSONArray) _params).get(0) + "";
    } else if (_params instanceof JSONObject) {
        numberString = ((JSONObject) _params).get("number") + "";
    } else {
        return new RpcMsg(null, RpcError.INVALID_PARAMS, "Invalid parameters");
    }

    // TODO: parse hex
    long number;
    try {
        number = Long.parseLong(numberString);
    } catch (NumberFormatException e) {
        return new RpcMsg(null, RpcError.INVALID_PARAMS, "Unable to decode input number");
    }
    Block block = this.ac.getBlockchain().getBlockByNumber(number);

    if (block == null) {
        return new RpcMsg(JSONObject.NULL);
    }

    return new RpcMsg(dumpBlock(block, false));
}
 
Example 7
Source File: Runtime.java    From weex with Apache License 2.0 5 votes vote down vote up
public RemoteObject objectForRemote(Object value) {
  RemoteObject result = new RemoteObject();
  if (value == null) {
    result.type = ObjectType.OBJECT;
    result.subtype = ObjectSubType.NULL;
    result.value = JSONObject.NULL;
  } else if (value instanceof Boolean) {
    result.type = ObjectType.BOOLEAN;
    result.value = value;
  } else if (value instanceof Number) {
    result.type = ObjectType.NUMBER;
    result.value = value;
  } else if (value instanceof Character) {
    // Unclear whether we should expose these as strings, numbers, or something else.
    result.type = ObjectType.NUMBER;
    result.value = Integer.valueOf(((Character)value).charValue());
  } else if (value instanceof String) {
    result.type = ObjectType.STRING;
    result.value = String.valueOf(value);
  } else {
    result.type = ObjectType.OBJECT;
    result.className = "What??";  // I have no idea where this is used.
    result.objectId = String.valueOf(mObjects.putObject(value));

    if (value.getClass().isArray()) {
      result.description = "array";
    } else if (value instanceof List) {
      result.description = "List";
    } else if (value instanceof Set) {
      result.description = "Set";
    } else if (value instanceof Map) {
      result.description = "Map";
    } else {
      result.description = getPropertyClassName(value);
    }

  }
  return result;
}
 
Example 8
Source File: JsonUtils.java    From LightningStorage with Apache License 2.0 5 votes vote down vote up
public Map<String, Object> jsonToMap(final JSONObject jsonObject) throws JSONException {
  Map<String, Object> retMap = new HashMap<>();

  if (jsonObject != JSONObject.NULL) {
    retMap = toMap(jsonObject);
  }
  return retMap;
}
 
Example 9
Source File: Response.java    From barterli_android with Apache License 2.0 5 votes vote down vote up
private static Response createResponseFromObject(Request request, HttpURLConnection connection, Object object,
        boolean isFromCache, Object originalResult) throws JSONException {
    if (object instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) object;

        FacebookRequestError error =
                FacebookRequestError.checkResponseAndCreateError(jsonObject, originalResult, connection);
        if (error != null) {
            if (error.getErrorCode() == INVALID_SESSION_FACEBOOK_ERROR_CODE) {
                Session session = request.getSession();
                if (session != null) {
                    session.closeAndClearTokenInformation();
                }
            }
            return new Response(request, connection, error);
        }

        Object body = Utility.getStringPropertyAsJSON(jsonObject, BODY_KEY, NON_JSON_RESPONSE_PROPERTY);

        if (body instanceof JSONObject) {
            GraphObject graphObject = GraphObject.Factory.create((JSONObject) body);
            return new Response(request, connection, graphObject, isFromCache);
        } else if (body instanceof JSONArray) {
            GraphObjectList<GraphObject> graphObjectList = GraphObject.Factory.createList(
                    (JSONArray) body, GraphObject.class);
            return new Response(request, connection, graphObjectList, isFromCache);
        }
        // We didn't get a body we understand how to handle, so pretend we got nothing.
        object = JSONObject.NULL;
    }

    if (object == JSONObject.NULL) {
        return new Response(request, connection, (GraphObject)null, isFromCache);
    } else {
        throw new FacebookException("Got unexpected object type in response, class: "
                + object.getClass().getSimpleName());
    }
}
 
Example 10
Source File: JsonValue.java    From json-schema with Apache License 2.0 5 votes vote down vote up
protected static Object deepToOrgJson(JsonValue v) {
    if (v.unwrap() == null) {
        return JSONObject.NULL;
    }
    if (v instanceof JsonObject) {
        JSONObject obj = new JSONObject();
        ((JsonObject) v).forEach((key, value) -> obj.put(key, deepToOrgJson(value)));
        return obj;
    } else if (v instanceof JsonArray) {
        JSONArray array = new JSONArray();
        ((JsonArray) v).forEach((index, value) -> array.put(deepToOrgJson(value)));
        return array;
    } else
        return v.unwrap();
}
 
Example 11
Source File: FileProperty.java    From androiddevice.info with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object getProperty() {
    try {
       return readFile(getFilename());
    } catch (Exception e) {
        return JSONObject.NULL;
    }
}
 
Example 12
Source File: ApiWeb3Aion.java    From aion with MIT License 5 votes vote down vote up
public RpcMsg eth_getTransactionReceipt(Object _params) {
    String _hash;
    if (_params instanceof JSONArray) {
        _hash = ((JSONArray) _params).get(0) + "";
    } else if (_params instanceof JSONObject) {
        _hash = ((JSONObject) _params).get("hash") + "";
    } else {
        return new RpcMsg(null, RpcError.INVALID_PARAMS, "Invalid parameters");
    }

    byte[] txHash = StringUtils.StringHexToByteArray(_hash);
    TxRecpt r = getTransactionReceipt(txHash);

    // commenting this out because of lack support for old web3 client that we are using
    // TODO: re-enable this when we upgrade our web3 client
    /*
    // if we can't find the receipt on the mainchain, try looking for it in pending receipts cache
    /*
    if (r == null) {
        AionTxReceipt pendingReceipt = pendingReceipts.get(new ByteArrayWrapper(txHash));
        r = new TxRecpt(pendingReceipt, null, null, null, true);
    }
    */

    if (r == null) {
        return new RpcMsg(
                JSONObject.NULL); // json rpc spec: 'or null when no receipt was found'
    }

    return new RpcMsg(r.toJson());
}
 
Example 13
Source File: BundleJSONConverter.java    From kognitivo with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 14
Source File: ApiWeb3Aion.java    From aion with MIT License 5 votes vote down vote up
public RpcMsg eth_getInternalTransactionsByHash(Object _params) {
    String _hash;
    try {
        if (_params instanceof JSONArray) {
            _hash = ((JSONArray) _params).get(0) + "";
        } else if (_params instanceof JSONObject) {
            _hash = ((JSONObject) _params).get("transactionHash") + "";
        } else {
            throw new Exception("Invalid input object provided");
        }
    } catch (Exception e) {
        LOG.debug("Error processing json input arguments", e);
        return new RpcMsg(null, RpcError.INVALID_PARAMS, "Invalid parameters");
    }

    byte[] txHash = ByteUtil.hexStringToBytes(_hash);
    if (_hash.equals("null") || txHash == null) {
        return null;
    }

    AionTxInfo txInfo = this.ac.getAionHub().getBlockchain().getTransactionInfo(txHash);
    if (txInfo == null) {
        return new RpcMsg(JSONObject.NULL); // json rpc spec: 'or null when no transaction was found'
    }

    Block b = this.ac.getBlockchain().getBlockByHash(txInfo.getBlockHash());
    if (b == null) {
        return null; // this is actually an internal error
    }

    return new RpcMsg(Tx.internalTxsToJSON(txInfo.getInternalTransactions(), txHash, txInfo.isCreatedWithInternalTransactions()));
}
 
Example 15
Source File: BeanToJsonConverter.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private Object mapObject(Object toConvert, int maxDepth, boolean skipNulls) throws Exception {
    if (maxDepth < 1) {
        return null;
    }

    // Raw object via reflection? Nope, not needed
    JSONObject mapped = new JSONObject();
    for (SimplePropertyDescriptor pd : SimplePropertyDescriptor.getPropertyDescriptors(toConvert.getClass())) {
        if ("class".equals(pd.getName())) {
            mapped.put("class", toConvert.getClass().getName());
            continue;
        }

        Method readMethod = pd.getReadMethod();
        if (readMethod == null) {
            continue;
        }

        if (readMethod.getParameterTypes().length > 0) {
            continue;
        }

        readMethod.setAccessible(true);

        Object result = readMethod.invoke(toConvert);
        result = convertObject(result, maxDepth - 1);
        if (!skipNulls || result != JSONObject.NULL) {
            mapped.put(pd.getName(), result);
        }
    }

    return mapped;
}
 
Example 16
Source File: ApiWeb3Aion.java    From aion with MIT License 5 votes vote down vote up
public RpcMsg eth_getBlockByHash(Object _params) {
    String _hash;
    boolean _fullTx;
    try {
        if (_params instanceof JSONArray) {
            _hash = ((JSONArray) _params).get(0) + "";
            _fullTx = ((JSONArray) _params).optBoolean(1, false);
        } else if (_params instanceof JSONObject) {
            _hash = ((JSONObject) _params).get("block") + "";
            _fullTx = ((JSONObject) _params).optBoolean("fullTransaction", false);
        } else {
            throw new Exception("Invalid input object provided");
        }
    } catch (Exception e) {
        LOG.debug("Error processing json input arguments", e);
        return new RpcMsg(null, RpcError.INVALID_PARAMS, "Invalid parameters");
    }

    Block block = ac.getBlockchain().getBlockWithInfoByHash(ByteUtil.hexStringToBytes(_hash));

    if (block == null) {
        LOG.debug("<get-block hash={} err=not-found>", _hash);
        return new RpcMsg(JSONObject.NULL); // json rpc spec: 'or null when no block was found'
    }

    return new RpcMsg(Blk.AionBlockToJson(block, _fullTx));
}
 
Example 17
Source File: ValidatingVisitor.java    From json-schema with Apache License 2.0 4 votes vote down vote up
@Override
void visitNullSchema(NullSchema nullSchema) {
    if (!(subject == null || subject == JSONObject.NULL)) {
        failureReporter.failure("expected: null, found: " + subject.getClass().getSimpleName(), "type");
    }
}
 
Example 18
Source File: AccessibilityHierarchyDumper.java    From screenshot-tests-for-android with Apache License 2.0 4 votes vote down vote up
private static Object jsonNullOr(Object obj) {
  return obj == null ? JSONObject.NULL : obj;
}
 
Example 19
Source File: Zipper.java    From equalize-xpi-modules with MIT License 4 votes vote down vote up
/**
     * Write a JSON Array.
     *
     * @param jsonarray The JSONArray to write.
     * @throws JSONException If the write fails.
     */
    private void write(JSONArray jsonarray) throws JSONException {

// JSONzip has three encodings for arrays:
// The array is empty (zipEmptyArray).
// First value in the array is a string (zipArrayString).
// First value in the array is not a string (zipArrayValue).

        boolean stringy = false;
        int length = jsonarray.length();
        if (length == 0) {
            write(zipEmptyArray, 3);
        } else {
            Object value = jsonarray.get(0);
            if (value == null) {
                value = JSONObject.NULL;
            }
            if (value instanceof String) {
                stringy = true;
                write(zipArrayString, 3);
                writeString((String) value);
            } else {
                write(zipArrayValue, 3);
                writeValue(value);
            }
            for (int i = 1; i < length; i += 1) {
                if (probe) {
                    log();
                }
                value = jsonarray.get(i);
                if (value == null) {
                    value = JSONObject.NULL;
                }
                if (value instanceof String != stringy) {
                    zero();
                }
                one();
                if (value instanceof String) {
                    writeString((String) value);
                } else {
                    writeValue(value);
                }
            }
            zero();
            zero();

        }
    }
 
Example 20
Source File: StrictJsonParser.java    From nakadi with MIT License 4 votes vote down vote up
private static Object readNullTillTheEnd(final StringTokenizer tokenizer) {
    if (!tokenizer.next(3).equals("ull")) {
        throw syntaxError("Expected null value", tokenizer);
    }
    return JSONObject.NULL;
}