Java 类com.google.gson.JsonNull 实例源码

项目:Phoenix-for-VK    文件:DboWrapperAdapter.java   
@Override
public EntityWrapper deserialize(JsonElement jsonElement, Type typef, JsonDeserializationContext context) throws JsonParseException {
    if (jsonElement == null || jsonElement instanceof JsonNull) {
        return null;
    }

    JsonObject root = jsonElement.getAsJsonObject();

    boolean isNull = root.get(KEY_IS_NULL).getAsBoolean();

    Entity entity = null;
    if (!isNull) {
        int dbotype = root.get(KEY_TYPE).getAsInt();
        entity = context.deserialize(root.get(KEY_ENTITY), AttachmentsTypes.classForType(dbotype));
    }

    return new EntityWrapper(entity);
}
项目:Phoenix-for-VK    文件:DboWrapperAdapter.java   
@Override
public JsonElement serialize(EntityWrapper wrapper, Type type, JsonSerializationContext context) {
    if (wrapper == null) {
        return JsonNull.INSTANCE;
    }

    JsonObject root = new JsonObject();

    Entity entity = wrapper.get();
    root.add(KEY_IS_NULL, new JsonPrimitive(entity == null));

    if (entity != null) {
        root.add(KEY_TYPE, new JsonPrimitive(AttachmentsTypes.typeForInstance(entity)));
        root.add(KEY_ENTITY, context.serialize(entity));
    }

    return root;
}
项目:ProjectAres    文件:ConfigUtils.java   
private static JsonElement toJson(Object value) {
    if(value instanceof ConfigurationSection) {
        return toJson((ConfigurationSection) value);
    } else if(value instanceof Map) {
        return toJson((Map) value);
    } else if(value instanceof List) {
        return toJson((List) value);
    } else if(value instanceof String) {
        return new JsonPrimitive((String) value);
    } else if(value instanceof Character) {
        return new JsonPrimitive((Character) value);
    } else if(value instanceof Number) {
        return new JsonPrimitive((Number) value);
    } else if(value instanceof Boolean) {
        return new JsonPrimitive((Boolean) value);
    } else if(value == null) {
        return JsonNull.INSTANCE;
    } else {
        throw new IllegalArgumentException("Cannot coerce " + value.getClass().getSimpleName() + " to JSON");
    }
}
项目:letv    文件:Streams.java   
public static JsonElement parse(JsonReader reader) throws JsonParseException {
    boolean isEmpty = true;
    try {
        reader.peek();
        isEmpty = false;
        return (JsonElement) TypeAdapters.JSON_ELEMENT.read(reader);
    } catch (Throwable e) {
        if (isEmpty) {
            return JsonNull.INSTANCE;
        }
        throw new JsonIOException(e);
    } catch (Throwable e2) {
        throw new JsonSyntaxException(e2);
    } catch (Throwable e22) {
        throw new JsonIOException(e22);
    } catch (Throwable e222) {
        throw new JsonSyntaxException(e222);
    }
}
项目:boohee_v5.6    文件:Streams.java   
public static JsonElement parse(JsonReader reader) throws JsonParseException {
    boolean isEmpty = true;
    try {
        reader.peek();
        isEmpty = false;
        return (JsonElement) TypeAdapters.JSON_ELEMENT.read(reader);
    } catch (Throwable e) {
        if (isEmpty) {
            return JsonNull.INSTANCE;
        }
        throw new JsonSyntaxException(e);
    } catch (Throwable e2) {
        throw new JsonSyntaxException(e2);
    } catch (Throwable e22) {
        throw new JsonIOException(e22);
    } catch (Throwable e222) {
        throw new JsonSyntaxException(e222);
    }
}
项目:nifi-nars    文件:JsonUtil.java   
public static JsonElement extractElement(JsonElement json, String field) {
    if (json == null) {
        return JsonNull.INSTANCE;
    }

    // We reached the field, return the leaf's value as a string
    if (!field.contains(".")) {
        if (json.isJsonObject()) {
            JsonElement element = ((JsonObject) json).get(field);
            return element == null ? JsonNull.INSTANCE : element;
        } else {
            return JsonNull.INSTANCE;
        }
    }

    int i = field.indexOf('.');
    String key = field.substring(i + 1, field.length());
    JsonElement value = ((JsonObject) json).get(field.substring(0, i));
    return extractElement(value, key);
}
项目:oson    文件:JsonArrayTest.java   
public void testEqualsNonEmptyArray() {
  JsonArray a = new JsonArray();
  JsonArray b = new JsonArray();

  assertEquals(a, a);

  a.add(new JsonObject());
  assertFalse(a.equals(b));
  assertFalse(b.equals(a));

  b.add(new JsonObject());
  assertEquals(oson.serialize(a), oson.serialize(b));

  a.add(new JsonObject());
  assertFalse(a.equals(b));
  assertFalse(b.equals(a));

  b.add(JsonNull.INSTANCE);
  assertNotEquals(oson.serialize(a), oson.serialize(b));
}
项目:twill    文件:ILoggingEventSerializer.java   
@Override
public JsonElement serialize(ILoggingEvent event, Type typeOfSrc, JsonSerializationContext context) {
  JsonObject json = new JsonObject();
  json.addProperty("name", event.getLoggerName());
  json.addProperty("host", hostname);
  json.addProperty("timestamp", Long.toString(event.getTimeStamp()));
  json.addProperty("level", event.getLevel().toString());
  json.addProperty("className", classNameConverter.convert(event));
  json.addProperty("method", methodConverter.convert(event));
  json.addProperty("file", fileConverter.convert(event));
  json.addProperty("line", lineConverter.convert(event));
  json.addProperty("thread", event.getThreadName());
  json.addProperty("message", event.getFormattedMessage());
  json.addProperty("runnableName", runnableName);
  if (event.getThrowableProxy() == null) {
    json.add("throwable", JsonNull.INSTANCE);
  } else {
    json.add("throwable", context.serialize(new DefaultLogThrowable(event.getThrowableProxy()), LogThrowable.class));
  }

  return json;
}
项目:cosmic    文件:Request.java   
@Override
public JsonElement serialize(final Pair<Long, Long> src, final java.lang.reflect.Type typeOfSrc, final JsonSerializationContext context) {
    final JsonArray array = new JsonArray();
    if (src.first() != null) {
        array.add(s_gson.toJsonTree(src.first()));
    } else {
        array.add(new JsonNull());
    }

    if (src.second() != null) {
        array.add(s_gson.toJsonTree(src.second()));
    } else {
        array.add(new JsonNull());
    }

    return array;
}
项目:seven-wonders    文件:ScienceProgressSerializer.java   
@Override
public JsonElement serialize(ScienceProgress scienceProgress, Type typeOfSrc, JsonSerializationContext context) {
    Science science = scienceProgress.getScience();

    if (science.size() > 1) {
        throw new UnsupportedOperationException("Cannot serialize science containing more than one element");
    }

    for (ScienceType type : ScienceType.values()) {
        int quantity = science.getQuantity(type);
        if (quantity == 1) {
            return context.serialize(type);
        }
    }

    if (science.getJokers() == 1) {
        return new JsonPrimitive("any");
    }

    return JsonNull.INSTANCE;
}
项目:Inferno    文件:PlayerHelper.java   
private static JsonArray serializeInventory(Inventory inv) {
    JsonArray json = new JsonArray();

    inv.slots().forEach(slot -> {
        Optional<ItemStack> item = slot.peek();
        if (item.isPresent()) {
            try {
                json.add(new JsonPrimitive(SerializationHelper.serialize(item.get())));
            } catch (IOException ex) {
                InfernoCore.logWarning("Failed to serialize ItemStack from inventory");
                ex.printStackTrace();
            }
        } else {
            json.add(JsonNull.INSTANCE);
        }
    });

    return json;
}
项目:ratebeer    文件:BeerOnTopListDeserializer.java   
@Override
public BeerOnTopList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonObject object = json.getAsJsonObject();
    BeerOnTopList beerOnTopList = new BeerOnTopList();
    beerOnTopList.beerId = object.get("BeerID").getAsInt();
    beerOnTopList.beerName = Normalizer.get().cleanHtml(object.get("BeerName").getAsString());
    if (object.has("BeerStyleID") && !(object.get("BeerStyleID") instanceof JsonNull))
        beerOnTopList.styleId = object.get("BeerStyleID").getAsInt();

    if (!(object.get("OverallPctl") instanceof JsonNull))
        beerOnTopList.overallPercentile = object.get("OverallPctl").getAsFloat();
    if (!(object.get("StylePctl") instanceof JsonNull))
        beerOnTopList.stylePercentile = object.get("StylePctl").getAsFloat();
    if (!(object.get("AverageRating") instanceof JsonNull))
        beerOnTopList.weightedRating = object.get("AverageRating").getAsFloat();
    beerOnTopList.rateCount = object.get("RateCount").getAsInt();
    if (object.has("HadIt") && !(object.get("HadIt") instanceof JsonNull))
        beerOnTopList.ratedByUser = object.get("HadIt").getAsInt() == 1;
    return beerOnTopList;
}
项目:ratebeer    文件:PlaceSearchResultDeserializer.java   
@Override
public PlaceSearchResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonObject object = json.getAsJsonObject();
    PlaceSearchResult placeSearchResult = new PlaceSearchResult();
    placeSearchResult.placeId = object.get("PlaceID").getAsInt();
    placeSearchResult.placeName = Normalizer.get().cleanHtml(object.get("PlaceName").getAsString());
    placeSearchResult.placeType = object.get("PlaceType").getAsInt();
    placeSearchResult.city = Normalizer.get().cleanHtml(object.get("City").getAsString());
    if (object.has("CountryID") && !(object.get("CountryID") instanceof JsonNull))
        placeSearchResult.countryId = object.get("CountryID").getAsInt();
    if (object.has("StateId") && !(object.get("StateID") instanceof JsonNull))
        placeSearchResult.stateId = object.get("StateID").getAsInt();
    if (object.has("Percentile") && !(object.get("Percentile") instanceof JsonNull))
        placeSearchResult.overallPercentile = object.get("Percentile").getAsFloat();
    if (object.has("AvgRating") && !(object.get("AvgRating") instanceof JsonNull))
        placeSearchResult.averageRating = object.get("AvgRating").getAsFloat();
    if (object.has("RateCount") && !(object.get("RateCount") instanceof JsonNull))
        placeSearchResult.rateCount = object.get("RateCount").getAsInt();
    return placeSearchResult;
}
项目:ratebeer    文件:BeerSearchResultDeserializer.java   
@Override
public BeerSearchResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonObject object = json.getAsJsonObject();
    BeerSearchResult beerSearchResult = new BeerSearchResult();
    beerSearchResult.beerId = object.get("BeerID").getAsInt();
    beerSearchResult.beerName = Normalizer.get().cleanHtml(object.get("BeerName").getAsString());
    beerSearchResult.brewerId = object.get("BrewerID").getAsInt();

    if (!(object.get("OverallPctl") instanceof JsonNull))
        beerSearchResult.overallPercentile = object.get("OverallPctl").getAsFloat();
    beerSearchResult.rateCount = object.get("RateCount").getAsInt();
    if (object.has("Unrateable") && !(object.get("Unrateable") instanceof JsonNull))
        beerSearchResult.unrateable = object.get("Unrateable").getAsBoolean();
    if (object.has("IsAlias") && !(object.get("IsAlias") instanceof JsonNull))
        beerSearchResult.alias = object.get("IsAlias").getAsBoolean();
    beerSearchResult.retired = object.get("Retired").getAsBoolean();
    if (object.has("IsRated") && !(object.get("IsRated") instanceof JsonNull))
        beerSearchResult.ratedByUser = object.get("IsRated").getAsInt() == 1;
    return beerSearchResult;
}
项目:ratebeer    文件:FeedItemDeserializer.java   
@Override
public FeedItem deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonObject object = json.getAsJsonObject();
    FeedItem feedItem = new FeedItem();
    feedItem.activityId = object.get("ActivityID").getAsInt();
    feedItem.userId = object.get("UserID").getAsInt();
    feedItem.userName = Normalizer.get().cleanHtml(object.get("Username").getAsString());
    feedItem.type = object.get("Type").getAsInt();
    if (!(object.get("LinkID") instanceof JsonNull))
        feedItem.linkId = object.get("LinkID").getAsInt();
    feedItem.linkText = object.get("LinkText").getAsString(); // Keep raw HTML
    if (!(object.get("ActivityNumber") instanceof JsonNull))
        feedItem.activityNumber = object.get("ActivityNumber").getAsInt();
    feedItem.timeEntered = Normalizer.get().parseTime(object.get("TimeEntered").getAsString());
    if (!(object.get("NumComments") instanceof JsonNull))
        feedItem.numComments = object.get("NumComments").getAsInt();
    return feedItem;
}
项目:ratebeer    文件:BeerRatingDeserializer.java   
@Override
public BeerRating deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonObject object = json.getAsJsonObject();
    BeerRating userRating = new BeerRating();
    userRating.ratingId = object.get("RatingID").getAsInt();
    userRating.userId = object.get("UserID").getAsInt();
    userRating.userName = Normalizer.get().cleanHtml(object.get("UserName").getAsString());
    if (object.get("CountryID") != null && !(object.get("CountryID") instanceof JsonNull))
        userRating.userCountryId = object.get("CountryID").getAsInt();
    if (object.get("Country") != null && !(object.get("Country") instanceof JsonNull))
        userRating.userCountryName = Normalizer.get().cleanHtml(object.get("Country").getAsString());
    userRating.userRateCount = object.get("RateCount").getAsInt();

    userRating.aroma = object.get("Aroma").getAsInt();
    userRating.flavor = object.get("Flavor").getAsInt();
    userRating.mouthfeel = object.get("Mouthfeel").getAsInt();
    userRating.appearance = object.get("Appearance").getAsInt();
    userRating.overall = object.get("Overall").getAsInt();
    userRating.total = object.get("TotalScore").getAsFloat();
    userRating.comments = Normalizer.get().cleanHtml(object.get("Comments").getAsString());
    userRating.timeEntered = Normalizer.get().parseTime(object.get("TimeEntered").getAsString());
    if (!(object.get("TimeUpdated") instanceof JsonNull))
        userRating.timeUpdated = Normalizer.get().parseTime(object.get("TimeUpdated").getAsString());
    return userRating;
}
项目:muninn    文件:JsonSerializationConfiguration.java   
private JsonElement fromJsonEvent(JsonEvent event) {
    JsonObject jsonObject = new JsonObject();

    if(event.getId().isPresent()) {
        jsonObject.add("id", new JsonPrimitive(event.getId().get()));
    } else {
        jsonObject.add("id", JsonNull.INSTANCE);
    }

    if(event.getFilterKey().isPresent()) {
        jsonObject.add("filterKey", new JsonPrimitive(event.getFilterKey().get()));
    } else {
        jsonObject.add("filterKey", JsonNull.INSTANCE);
    }

    jsonObject.add("value", event.getValue());

    return jsonObject;
}
项目:json-mystique    文件:JsonLever.java   
/**
 * Gets the json element in the specified jpath.
 *
 * @param source the source
 * @param jpath the fully qualified json path to the field required. eg get({'a': {'b': {'c': [1,
 *     2, 3, 4]}}}, ["a", "b" "c", 1]) is '2'. Array indexes need to be specified as numerals.
 *     Strings are always presumed to be field names.
 * @return the json element returns 'Null' for any invalid path return the source if the input
 *     jpath is '.'
 */
public JsonElement get(JsonElement source, JsonArray jpath) {
  JsonElement result = JsonNull.INSTANCE;
  if (isNotNull(jpath)) {
    result = source;
    for (JsonElement path : jpath) {
      try {
        if (isNumber(path)) {
          result = result.getAsJsonArray().get(path.getAsInt());
        } else {
          result = result.getAsJsonObject().get(path.getAsString());
        }
      } catch (Exception e) {
        return JsonNull.INSTANCE;
      }
    }
  }

  return result;
}
项目:json-mystique    文件:JsonLever.java   
/**
 * Gets the typed path.
 *
 * @param p the p
 * @param strToNum the str to num
 * @return the typed path
 */
private JsonElement getTypedPath(Object p, Boolean strToNum) {
  JsonElement result = JsonNull.INSTANCE;
  if (p instanceof Number) {
    result = new JsonPrimitive((Number) p);
  } else if (p instanceof String) {
    String sp = StringUtils.trimToEmpty((String) p);
    result =
        strToNum
            ? (NumberUtils.isCreatable(sp)
                ? new JsonPrimitive(NumberUtils.toInt(sp))
                : new JsonPrimitive(sp))
            : new JsonPrimitive(sp);
  } else if (p instanceof Boolean) {
    result = new JsonPrimitive((Boolean) p);
  } else if (p instanceof Character) {
    result = new JsonPrimitive((Character) p);
  } else if (p instanceof JsonElement) {
    result = (JsonElement) p;
  }
  return result;
}
项目:json-mystique    文件:JsonLever.java   
/**
 * Replete array.
 *
 * @param source the source
 * @param index the index
 * @param type the type
 * @return the json array
 */
private JsonArray repleteArray(
    JsonArray source, Integer index, Class<? extends JsonElement> type) {
  source = isNull(source) ? new JsonArray() : source;
  for (int i = 0; i <= index; i++) {
    try {
      source.get(i);
    } catch (IndexOutOfBoundsException e) {
      Class<? extends JsonElement> newType = JsonNull.class;
      if (i == index) {
        newType = type;
      }
      source.add(getNewElement(newType));
    }
  }
  if (!source.get(index).getClass().equals(type)) {
    log.warn(
        String.format(
            "The element at index %s in the source %s, does not match %s. Creating a new element.",
            index, source, type));
    source.add(getNewElement(type));
  }
  return source;
}
项目:json-mystique    文件:JsonLever.java   
/**
 * Jsonify.
 *
 * @param source the source
 * @return the json element
 */
public JsonElement jsonify(Object source) {
  JsonElement result = JsonNull.INSTANCE;
  if (source instanceof JsonElement) {
    result = (JsonElement) source;
  } else {
    try {
      result = GsonConvertor.getInstance().deserialize(source, JsonElement.class);

    } catch (ConvertorException e) {
      String msg = String.format("Could not deserialise object %s to json.", source);
      log.error(msg);
      log.debug(msg, e);
    }
  }
  return result;
}
项目:json-mystique    文件:JsonLever.java   
/**
 * Gets the new element.
 *
 * @param type the type
 * @return the new element
 */
private JsonElement getNewElement(Class<? extends JsonElement> type) {
  JsonElement element = JsonNull.INSTANCE;
  if (JsonObject.class.equals(type)) {
    element = new JsonObject();
  } else if (JsonArray.class.equals(type)) {
    element = new JsonArray();
  } else {
    try {
      element = type.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
      log.error(String.format("Could not instantiate json element of type %s", type));
      log.debug(String.format("Could not instantiate json element of type %s.", type), e);
    }
  }
  return element;
}
项目:json-mystique    文件:AbstractMystTurn.java   
/**
 * Transform on condition.
 *
 * @param conditionalJson the conditional json
 * @param source the source
 * @param deps the deps
 * @param aces the aces
 * @param resultWrapper the result wrapper
 * @return the json element
 */
protected JsonElement transformToDefault(
    JsonObject conditionalJson,
    List<JsonElement> source,
    JsonObject deps,
    JsonObject aces,
    JsonObject resultWrapper) {
  JsonElement transform = JsonNull.INSTANCE;
  if (mystiqueLever.isNotNull(conditionalJson)) {
    // Should not be null, can be json null
    JsonElement value = conditionalJson.get(MystiqueConstants.VALUE);
    if (null != value) {
      transform = value;
    } else {
      JsonObject defaultTurn =
          mystiqueLever.asJsonObject(conditionalJson.get(MystiqueConstants.TURN));
      if (mystiqueLever.isNotNull(defaultTurn)) {
        MystTurn mystique = factory.getMystTurn(defaultTurn);
        transform = mystique.transform(source, deps, aces, defaultTurn, resultWrapper);
      }
    }
  }
  return transform;
}
项目:sociallink    文件:JsonObjectProcessor.java   
@SuppressWarnings("unchecked")
default <T> T get(final JsonElement json, final Class<T> clazz, final String... path) {
    JsonElement result = json;
    for (final String element : path) {
        result = result instanceof JsonObject ? ((JsonObject) result).get(element) : null;
    }
    if (result == null || result instanceof JsonNull) {
        return null;
    } else if (clazz.isInstance(result)) {
        return clazz.cast(result);
    } else if (clazz == Long.class) {
        return (T) (Long) result.getAsLong();
    } else if (clazz == String.class) {
        return (T) result.getAsString();
    } else if (clazz == Integer.class) {
        return (T) (Integer) result.getAsInt();
    } else {
        throw new UnsupportedOperationException(clazz.getName());
    }
}
项目:blogwt    文件:AndroidMessage.java   
@Override
public JsonObject toJson () {
    JsonObject object = super.toJson();
    JsonElement jsonAndroid_channel_id = android_channel_id == null
            ? JsonNull.INSTANCE : new JsonPrimitive(android_channel_id);
    object.add("android_channel_id", jsonAndroid_channel_id);
    JsonElement jsonIcon = icon == null ? JsonNull.INSTANCE
            : new JsonPrimitive(icon);
    object.add("icon", jsonIcon);
    JsonElement jsonTag = tag == null ? JsonNull.INSTANCE
            : new JsonPrimitive(tag);
    object.add("tag", jsonTag);
    JsonElement jsonColor = color == null ? JsonNull.INSTANCE
            : new JsonPrimitive(color);
    object.add("color", jsonColor);
    return object;
}
项目:JJV    文件:NotNullValidatorTest.java   
@Test
public void testValidate() {
    JsonValidator validator = new JsonValidator();
    validator.addValidator("someField", new NotNullValidator());

    JsonObject obj = new JsonObject();

    JsonValidationResult result = validator.validate(obj);
    Assert.assertEquals(true, result.hasErrors());
    Assert.assertEquals(1, result.fieldsInError().size());
    Assert.assertEquals("someField", result.fieldsInError().get(0));
    Assert.assertEquals("NotNull", result.getError("someField"));

    obj = new JsonObject();
    obj.add("someField", JsonNull.INSTANCE);

    result = validator.validate(obj);
    Assert.assertEquals(true, result.hasErrors());

    obj = new JsonObject();
    obj.addProperty("someField", "Some content");

    result = validator.validate(obj);
    Assert.assertEquals(false, result.hasErrors());
}
项目:blogwt    文件:GetPagesRequest.java   
@Override
public JsonObject toJson () {
    JsonObject object = super.toJson();
    JsonElement jsonParent = parent == null ? JsonNull.INSTANCE : parent
            .toJson();
    object.add("parent", jsonParent);
    JsonElement jsonIncludePosts = includePosts == null ? JsonNull.INSTANCE
            : new JsonPrimitive(includePosts);
    object.add("includePosts", jsonIncludePosts);
    JsonElement jsonPager = pager == null ? JsonNull.INSTANCE : pager
            .toJson();
    object.add("pager", jsonPager);
    JsonElement jsonQuery = query == null ? JsonNull.INSTANCE
            : new JsonPrimitive(query);
    object.add("query", jsonQuery);
    return object;
}
项目:CurseGraph    文件:Utils.java   
public static JsonElement fromJsonFile(File file)
{
    if(!file.exists())
    {
        return JsonNull.INSTANCE;
    }

    try
    {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        JsonElement e = new JsonParser().parse(reader);
        reader.close();
        return e;
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }

    return JsonNull.INSTANCE;
}
项目:CurseGraph    文件:Utils.java   
public static JsonElement fromJsonURL(String s)
{
    try
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(s).openStream()));
        JsonElement e = new JsonParser().parse(reader);
        reader.close();
        return e;
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }

    return JsonNull.INSTANCE;
}
项目:che    文件:GsonJsonRpcMarshaller.java   
private JsonElement getJsonElement(Object param) {
  if (param == null) {
    return JsonNull.INSTANCE;
  }
  if (param instanceof JsonElement) {
    return cast(param);
  }
  if (param instanceof String) {
    return new JsonPrimitive((String) param);
  }
  if (param instanceof Boolean) {
    return new JsonPrimitive((Boolean) param);
  }
  if (param instanceof Double) {
    return new JsonPrimitive((Double) param);
  }
  try {
    return jsonParser.parse(DtoFactory.getInstance().toJson(param));
  } catch (IllegalArgumentException e) {
    return gson.toJsonTree(param);
  }
}
项目:blogwt    文件:GetResourcesResponse.java   
@Override
public JsonObject toJson () {
    JsonObject object = super.toJson();
    JsonElement jsonResources = JsonNull.INSTANCE;
    if (resources != null) {
        jsonResources = new JsonArray();
        for (int i = 0; i < resources.size(); i++) {
            JsonElement jsonResourcesItem = resources.get(i) == null ? JsonNull.INSTANCE
                    : resources.get(i).toJson();
            ((JsonArray) jsonResources).add(jsonResourcesItem);
        }
    }
    object.add("resources", jsonResources);
    JsonElement jsonPager = pager == null ? JsonNull.INSTANCE : pager
            .toJson();
    object.add("pager", jsonPager);
    return object;
}
项目:dolphin-platform    文件:EventStreamSerializer.java   
private JsonObject convertToJson(final DolphinEvent<?> event) throws IOException {
    final JsonObject root = new JsonObject();

    root.addProperty(SPEC_VERSION_PARAM, SPEC_1_0);

    final Serializable data = event.getData();
    if (data != null) {
        root.addProperty(DATA_PARAM, Base64Utils.toBase64(data));
    } else {
        root.add(DATA_PARAM, JsonNull.INSTANCE);
    }

    root.add(CONTEXT_PARAM, convertToJson(event.getMessageEventContext()));

    return root;
}
项目:dolphin-platform    文件:EventStreamSerializerTests.java   
@Test
public void testEventWithNullDataFromJson() throws IOException, ClassNotFoundException {
    //given
    final Topic<String> topic = Topic.create("test-topic");
    final long timestamp = System.currentTimeMillis();

    final JsonObject root = new JsonObject();
    root.addProperty(SPEC_VERSION_PARAM, SPEC_1_0);
    root.add(DATA_PARAM, JsonNull.INSTANCE);
    final JsonObject context = new JsonObject();
    context.addProperty(TIMESTAMP_PARAM, timestamp);
    context.addProperty(TOPIC_PARAM, topic.getName());
    context.add(METADATA_PARAM, new JsonArray());
    root.add(CONTEXT_PARAM, context);
    checkJsonSchema(root);

    //when
    final DolphinEvent<?> event = convertToEvent(root);

    //then
    Assert.assertEquals(event.getData(), null);
}
项目:blogwt    文件:GetNotificationSettingsResponse.java   
@Override
public JsonObject toJson () {
    JsonObject object = super.toJson();
    JsonElement jsonPager = pager == null ? JsonNull.INSTANCE
            : pager.toJson();
    object.add("pager", jsonPager);
    JsonElement jsonSettings = JsonNull.INSTANCE;
    if (settings != null) {
        jsonSettings = new JsonArray();
        for (int i = 0; i < settings.size(); i++) {
            JsonElement jsonSettingsItem = settings.get(i) == null
                    ? JsonNull.INSTANCE : settings.get(i).toJson();
            ((JsonArray) jsonSettings).add(jsonSettingsItem);
        }
    }
    object.add("settings", jsonSettings);
    return object;
}
项目:B2C-NativeClient-Android    文件:LongSerializer.java   
/**
 * Serializes a Long instance to a JsonElement, verifying the maximum and
 * minimum allowed values
 */
@Override
public JsonElement serialize(Long element, Type type,
        JsonSerializationContext ctx) {
    Long maxAllowedValue = 0x0020000000000000L;
    Long minAllowedValue = Long.valueOf(0xFFE0000000000000L);
    if (element != null) {
        if (element > maxAllowedValue || element < minAllowedValue) {
            throw new InvalidParameterException(
                    "Long value must be between " + minAllowedValue
                            + " and " + maxAllowedValue);
        } else {
            return new JsonPrimitive(element);
        }
    } else {
        return JsonNull.INSTANCE;
    }

}
项目:telekom-workflow-engine    文件:JsonUtil.java   
private static JsonElement convert( Object object, Class<?> type, boolean serializeType ){
    if( object == null ){
        return JsonNull.INSTANCE;
    }
    else if( isSimple( object.getClass() ) ){
        return convertSimple( object, type, serializeType );
    }
    else if( isArray( object.getClass() ) ){
        return convertArray( object, type, serializeType );
    }
    else if( isCollection( object.getClass() ) ){
        return convertCollection( object, type, serializeType, true );
    }
    else if( isMap( object.getClass() ) ){
        return convertMap( object, type, serializeType );
    }
    else{
        return convertObject( object, type, serializeType );
    }
}
项目:blogwt    文件:GetPostsResponse.java   
@Override
public JsonObject toJson () {
    JsonObject object = super.toJson();
    JsonElement jsonPosts = JsonNull.INSTANCE;
    if (posts != null) {
        jsonPosts = new JsonArray();
        for (int i = 0; i < posts.size(); i++) {
            JsonElement jsonPostsItem = posts.get(i) == null ? JsonNull.INSTANCE
                    : posts.get(i).toJson();
            ((JsonArray) jsonPosts).add(jsonPostsItem);
        }
    }
    object.add("posts", jsonPosts);
    JsonElement jsonPager = pager == null ? JsonNull.INSTANCE : pager
            .toJson();
    object.add("pager", jsonPager);
    return object;
}
项目:blogwt    文件:Pager.java   
@Override
public JsonObject toJson () {
    JsonObject object = super.toJson();
    JsonElement jsonStart = start == null ? JsonNull.INSTANCE
            : new JsonPrimitive(start);
    object.add("start", jsonStart);
    JsonElement jsonCount = count == null ? JsonNull.INSTANCE
            : new JsonPrimitive(count);
    object.add("count", jsonCount);
    JsonElement jsonSortBy = sortBy == null ? JsonNull.INSTANCE
            : new JsonPrimitive(sortBy);
    object.add("sortBy", jsonSortBy);
    JsonElement jsonSortDirection = sortDirection == null ? JsonNull.INSTANCE
            : new JsonPrimitive(sortDirection.toString());
    object.add("sortDirection", jsonSortDirection);
    JsonElement jsonTotalCount = totalCount == null ? JsonNull.INSTANCE
            : new JsonPrimitive(totalCount);
    object.add("totalCount", jsonTotalCount);
    JsonElement jsonNext = next == null ? JsonNull.INSTANCE
            : new JsonPrimitive(next);
    object.add("next", jsonNext);
    JsonElement jsonPrevious = previous == null ? JsonNull.INSTANCE
            : new JsonPrimitive(previous);
    object.add("previous", jsonPrevious);
    return object;
}
项目:blogwt    文件:Form.java   
@Override
public JsonObject toJson () {
    JsonObject object = super.toJson();
    JsonElement jsonName = name == null ? JsonNull.INSTANCE
            : new JsonPrimitive(name);
    object.add("name", jsonName);
    JsonElement jsonFields = JsonNull.INSTANCE;
    if (fields != null) {
        jsonFields = new JsonArray();
        for (int i = 0; i < fields.size(); i++) {
            JsonElement jsonFieldsItem = fields.get(i) == null ? JsonNull.INSTANCE
                    : fields.get(i).toJson();
            ((JsonArray) jsonFields).add(jsonFieldsItem);
        }
    }
    object.add("fields", jsonFields);
    return object;
}
项目:blogwt    文件:GetRatingsRequest.java   
@Override
public JsonObject toJson () {
    JsonObject object = super.toJson();
    JsonElement jsonBy = by == null ? JsonNull.INSTANCE : by.toJson();
    object.add("by", jsonBy);
    JsonElement jsonSubjectId = subjectId == null ? JsonNull.INSTANCE
            : new JsonPrimitive(subjectId);
    object.add("subjectId", jsonSubjectId);
    JsonElement jsonSubjectType = subjectType == null ? JsonNull.INSTANCE
            : new JsonPrimitive(subjectType);
    object.add("subjectType", jsonSubjectType);
    JsonElement jsonPager = pager == null ? JsonNull.INSTANCE
            : pager.toJson();
    object.add("pager", jsonPager);
    return object;
}