Package com.restfb.json

Examples of com.restfb.json.JsonObject


              false,
              null,
              parametersWithAdditionalParameter(Parameter.with(FQL_QUERY_PARAM_NAME, queriesToJson(queries)),
                parameters)), JsonObject.class);

      JsonObject normalizedJson = new JsonObject();

      for (int i = 0; i < jsonObjects.size(); i++) {
        JsonObject jsonObject = jsonObjects.get(i);

        // For empty resultsets, Facebook will return an empty object instead of
        // an empty list. Hack around that here.
        JsonArray resultsArray =
            jsonObject.get("fql_result_set") instanceof JsonArray ? jsonObject.getJsonArray("fql_result_set")
                : new JsonArray();

        normalizedJson.put(jsonObject.getString("name"), resultsArray);
      }

      return objectType.equals(JsonObject.class) ? (T) normalizedJson : jsonMapper.toJavaObject(
        normalizedJson.toString(), objectType);
    } catch (JsonException e) {
View Full Code Here


    String encodedPayload = signedRequestTokens[1];
    String urlDecodedPayload = urlDecodeSignedRequestToken(encodedPayload);
    String payload = StringUtils.toString(decodeBase64(urlDecodedPayload));

    // Convert payload to a JsonObject so we can pull algorithm data out of it
    JsonObject payloadObject = getJsonMapper().toJavaObject(payload, JsonObject.class);

    if (!payloadObject.has("algorithm"))
      throw new FacebookSignedRequestParsingException("Unable to detect algorithm used for signed request");

    String algorithm = payloadObject.getString("algorithm");

    if (!verifySignedRequest(appSecret, algorithm, encodedPayload, signature))
      throw new FacebookSignedRequestVerificationException(
        "Signed request verification failed. Are you sure the request was made for the app identified by the app secret you provided?");
View Full Code Here

   */
  public DebugTokenInfo debugToken(String inputToken) {
    verifyParameterPresence("inputToken", inputToken);

    String response = makeRequest("/debug_token", Parameter.with("input_token", inputToken));
    JsonObject json = new JsonObject(response);
    JsonObject data = json.getJsonObject("data");

    try {
      return getJsonMapper().toJavaObject(data.toString(), DebugTokenInfo.class);
    } catch (Throwable t) {
      throw new FacebookResponseContentException("Unable to parse JSON from response.", t);
    }
  }
View Full Code Here

      // connections and in a few other places, e.g. comments on the Post
      // object.
      // Doing this simplifies mapping, so we don't have to worry about having a
      // little placeholder object that only has a "data" value.
      try {
        JsonObject jsonObject = new JsonObject(json);
        String[] fieldNames = JsonObject.getNames(jsonObject);

        if (fieldNames != null) {
          boolean hasSingleDataProperty = fieldNames.length == 1 && "data".equals(fieldNames[0]);
          Object jsonDataObject = jsonObject.get("data");

          if (!hasSingleDataProperty && !(jsonDataObject instanceof JsonArray))
            if (jsonMappingErrorHandler.handleMappingError(json, type, null))
              return null;
            else
View Full Code Here

            + "- you should map it as a List instead. Offending JSON is '" + json + "'.");

    try {
      // Are we asked to map to JsonObject? If so, short-circuit right away.
      if (type.equals(JsonObject.class))
        return (T) new JsonObject(json);

      List<FieldWithAnnotation<Facebook>> fieldsWithAnnotation = findFieldsWithAnnotation(type, Facebook.class);
      Set<String> facebookFieldNamesWithMultipleMappings = facebookFieldNamesWithMultipleMappings(fieldsWithAnnotation);

      // If there are no annotated fields, assume we're mapping to a built-in
      // type. If this is actually the empty object, just return a new instance
      // of the corresponding Java type.
      if (fieldsWithAnnotation.size() == 0)
        if (isEmptyObject(json)) {
          T instance = createInstance(type);

          // If there are any methods annotated with @JsonMappingCompleted,
          // invoke them.
          invokeJsonMappingCompletedMethods(instance);

          return instance;
        } else {
          return toPrimitiveJavaType(json, type);
        }

      // Facebook will sometimes return the string "null".
      // Check for that and bail early if we find it.
      if ("null".equals(json))
        return null;

      // Facebook will sometimes return the string "false" to mean null.
      // Check for that and bail early if we find it.
      if ("false".equals(json)) {
        if (logger.isLoggable(FINE))
          logger.fine("Encountered 'false' from Facebook when trying to map to " + type.getSimpleName()
              + " - mapping null instead.");
        return null;
      }

      JsonObject jsonObject = new JsonObject(json);
      T instance = createInstance(type);

      if (instance instanceof JsonObject)
        return (T) jsonObject;

      // For each Facebook-annotated field on the current Java object, pull data
      // out of the JSON object and put it in the Java object
      for (FieldWithAnnotation<Facebook> fieldWithAnnotation : fieldsWithAnnotation) {
        String facebookFieldName = getFacebookFieldName(fieldWithAnnotation);

        if (!jsonObject.has(facebookFieldName)) {
          if (logger.isLoggable(FINER))
            logger.finer("No JSON value present for '" + facebookFieldName + "', skipping. JSON is '" + json + "'.");

          continue;
        }
View Full Code Here

      return jsonArray;
    }

    if (object instanceof Map<?, ?>) {
      JsonObject jsonObject = new JsonObject();
      for (Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
        if (!(entry.getKey() instanceof String))
          throw new FacebookJsonMappingException("Your Map keys must be of type " + String.class
              + " in order to be converted to JSON.  Offending map is " + object);

        try {
          jsonObject.put((String) entry.getKey(), toJsonInternal(entry.getValue(), ignoreNullValuedProperties));
        } catch (JsonException e) {
          throw new FacebookJsonMappingException("Unable to process value '" + entry.getValue() + "' for key '"
              + entry.getKey() + "' in Map " + object, e);
        }
      }

      return jsonObject;
    }

    if (isPrimitive(object))
      return object;

    if (object instanceof BigInteger)
      return ((BigInteger) object).longValue();

    if (object instanceof BigDecimal)
      return ((BigDecimal) object).doubleValue();

    // We've passed the special-case bits, so let's try to marshal this as a
    // plain old Javabean...

    List<FieldWithAnnotation<Facebook>> fieldsWithAnnotation =
        findFieldsWithAnnotation(object.getClass(), Facebook.class);

    JsonObject jsonObject = new JsonObject();

    // No longer throw an exception in this case. If there are multiple fields
    // with the same @Facebook value, it's luck of the draw which is picked for
    // JSON marshaling.
    // TODO: A better implementation would query each duplicate-mapped field. If
    // it has is a non-null value and the other duplicate values are null, use
    // the non-null field.
    Set<String> facebookFieldNamesWithMultipleMappings = facebookFieldNamesWithMultipleMappings(fieldsWithAnnotation);
    if (facebookFieldNamesWithMultipleMappings.size() > 0 && logger.isLoggable(FINE))
      logger.fine(format("Unable to convert to JSON because multiple @" + Facebook.class.getSimpleName()
          + " annotations for the same name are present: " + facebookFieldNamesWithMultipleMappings));

    for (FieldWithAnnotation<Facebook> fieldWithAnnotation : fieldsWithAnnotation) {
      String facebookFieldName = getFacebookFieldName(fieldWithAnnotation);
      fieldWithAnnotation.getField().setAccessible(true);

      try {
        Object fieldValue = fieldWithAnnotation.getField().get(object);

        if (!(ignoreNullValuedProperties && fieldValue == null))
          jsonObject.put(facebookFieldName, toJsonInternal(fieldValue, ignoreNullValuedProperties));
      } catch (Exception e) {
        throw new FacebookJsonMappingException("Unable to process field '" + facebookFieldName + "' for "
            + object.getClass(), e);
      }
    }
View Full Code Here

      if (logger.isLoggable(FINE))
        logger.fine("Encountered comment array '" + rawValueAsString + "' but expected a "
            + Comments.class.getSimpleName() + " object instead.  Working around that " + "by coercing into an empty "
            + Comments.class.getSimpleName() + " instance...");

      JsonObject workaroundJsonObject = new JsonObject();
      workaroundJsonObject.put("total_count", 0);
      workaroundJsonObject.put("data", new JsonArray());
      rawValueAsString = workaroundJsonObject.toString();
    }

    // Some other type - recurse into it
    return toJavaObject(rawValueAsString, type);
  }
View Full Code Here

            + "Specify your queries in the Map that gets passed to this method.");

      parameters.add(additionalParameter);
    }

    JsonObject normalizedJson = new JsonObject();

    try {
      JsonArray jsonArray =
          new JsonArray(makeRequest("fql.multiquery", sessionKey, parameters.toArray(new Parameter[0])));

      for (int i = 0; i < jsonArray.length(); i++) {
        JsonObject jsonObject = jsonArray.getJsonObject(i);

        // For empty resultsets, Facebook will return an empty object instead of
        // an empty list. Hack around that here.
        JsonArray resultsArray =
            jsonObject.get("fql_result_set") instanceof JsonArray ? jsonObject.getJsonArray("fql_result_set")
                : new JsonArray();

        normalizedJson.put(jsonObject.getString("name"), resultsArray);
      }
    } catch (JsonException e) {
      throw new FacebookJsonMappingException("Unable to process fql.multiquery JSON response", e);
    }
View Full Code Here

    List<String> ids = new ArrayList<String>();
    ids.add("btaylor");
    ids.add("http://www.imdb.com/title/tt0117500/");

    // Make the API call
    JsonObject results = facebookClient.fetchObjects(ids, JsonObject.class);

    // Pull out JSON data by key and map each type by hand.
    JsonMapper jsonMapper = new DefaultJsonMapper();
    User user = jsonMapper.toJavaObject(results.getString("btaylor"), User.class);
    Url url = jsonMapper.toJavaObject(results.getString("http://www.imdb.com/title/tt0117500/"), Url.class);

    out.println("User is " + user);
    out.println("URL is " + url);
  }
View Full Code Here

  }

  void fetchDifferentDataTypesAsJsonObject() {
    out.println("* Fetching different types of data as JsonObject *");

    JsonObject btaylor = facebookClient.fetchObject("btaylor", JsonObject.class);
    out.println(btaylor.getString("name"));

    JsonObject photosConnection = facebookClient.fetchObject("me/photos", JsonObject.class);
    JsonArray photosConnectionData = photosConnection.getJsonArray("data");

    if (photosConnectionData.length() > 0) {
      String firstPhotoUrl = photosConnectionData.getJsonObject(0).getString("source");
      out.println(firstPhotoUrl);
    }
View Full Code Here

TOP

Related Classes of com.restfb.json.JsonObject

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.