Java Code Examples for com.google.gson.JsonObject.addProperty()

The following are Jave code examples for showing how to use addProperty() of the com.google.gson.JsonObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: li-android-sdk-core   File: LiQueryBuilder.java   View Source Code Vote up 8 votes
/**
 * Overrides default setting with the settings fetched fron the community.
 *
 * @param clientSettings    Local settings to be used.
 * @param serverSettingJson Settings received from community.
 */
private static void overrideDefaultSettings(JsonObject clientSettings, JsonObject serverSettingJson) {
    if (serverSettingJson != null && !serverSettingJson.isJsonNull()) {
        if (serverSettingJson.has("response_limit")) {
            int limit = serverSettingJson.get("response_limit").getAsInt();
            clientSettings.addProperty("limit", limit);
        }

        if (serverSettingJson.has("discussion_style")) {
            JsonArray discussionStyleArr = serverSettingJson.get("discussion_style").getAsJsonArray();
            StringBuilder conversationStyleSB = new StringBuilder();
            boolean isFirst = true;
            conversationStyleSB.append("(");
            for (JsonElement styleElem : discussionStyleArr) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    conversationStyleSB.append(", ");
                }
                conversationStyleSB.append("'").append(styleElem.getAsString()).append("'");
            }
            conversationStyleSB.append(")");
            if (clientSettings.has("whereClauses")) {
                JsonArray whereArr = clientSettings.get("whereClauses").getAsJsonArray();
                for (JsonElement whereElem : whereArr) {
                    JsonObject whereObj = whereElem.getAsJsonObject();
                    if (whereObj.has("key")) {
                        String key = whereObj.get("key").getAsString();
                        if (key.equals("conversation.style")) {
                            whereObj.addProperty("value", conversationStyleSB.toString());
                        }
                    }
                }
            }
        }
    }
}
 
Example 2
Project: HuskyCrates-Sponge   File: Metrics.java   View Source Code Vote up 6 votes
private JsonObject getRequestJsonObject(Logger logger, boolean logFailedRequests) {
    JsonObject chart = new JsonObject();
    chart.addProperty("chartId", chartId);
    try {
        JsonObject data = getChartData();
        if (data == null) {
            // If the data is null we don't send the chart.
            return null;
        }
        chart.add("data", data);
    } catch (Throwable t) {
        if (logFailedRequests) {
            logger.warn("Failed to get data for custom chart with id {}", chartId, t);
        }
        return null;
    }
    return chart;
}
 
Example 3
Project: TeamNote   File: GroupChatDaoImplTest.java   View Source Code Vote up 6 votes
@Test
public void testUpdateGroupChat() {
    JsonObject json = new JsonObject();
    json.addProperty("userId", 1);
    json.addProperty("datetime", new Date().toString());
    json.addProperty("content", "haha");
    ArrayList<String> chats = new ArrayList<String>();
    chats.add(json.toString());
    GroupChat groupChat = new GroupChat(1, chats);

    groupChatDao.addGroupChat(groupChat);
    groupChat = groupChatDao.getAllGroupChats().get(0);
    ArrayList<String> newList = new ArrayList<String>();
    newList.add("hhh");
    groupChat.setContents(newList);
    groupChatDao.updateGroupChat(groupChat);

    Assert.assertEquals(groupChatDao.getAllGroupChats().get(0).getContents(), newList);

    groupChatDao.deleteGroupChat(groupChat);
}
 
Example 4
Project: Proyecto-DASI   File: ObservationFromDiscreteCellImplementation.java   View Source Code Vote up 5 votes
@Override
public void writeObservationsToJSON(JsonObject json, MissionInit missionInit)
{
	// Return a string that is unique for every cell on the x/z plane (ignores y)
	EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;
	// getPosition() rounds to int.
	int x = player.getPosition().getX();
	int z = player.getPosition().getZ();
	json.addProperty("cell", "(" + x + "," + z + ")");
}
 
Example 5
Project: iot-edge-greengrass   File: JsonTuples.java   View Source Code Vote up 5 votes
private static void addAggStdInfo(JsonObject jo, List<JsonObject> samples) {
    // beginMsec, endMsec, nSamples
    long msec = samples.get(0).get(KEY_TS).getAsLong();
    long msec2 = samples.get(samples.size()-1).get(KEY_TS).getAsLong();
    int nSamples = samples.size();
    
    jo.addProperty(KEY_TS, msec2);
    jo.addProperty(KEY_AGG_BEGIN_TS, msec);
    jo.addProperty(KEY_AGG_COUNT, nSamples);
}
 
Example 6
Project: TeamNote   File: AdminController.java   View Source Code Vote up 5 votes
@RequestMapping("/banNote")
@ResponseBody
public String banNote(@RequestParam("verifyId") int verifyId) {
    adminService.banNote(verifyId);
    JsonObject obj = new JsonObject();
    obj.addProperty("result","success");
    return new Gson().toJson(obj);
}
 
Example 7
Project: Backmemed   File: UserListOpsEntry.java   View Source Code Vote up 5 votes
protected void onSerialization(JsonObject data)
{
    if (this.getValue() != null)
    {
        data.addProperty("uuid", ((GameProfile)this.getValue()).getId() == null ? "" : ((GameProfile)this.getValue()).getId().toString());
        data.addProperty("name", ((GameProfile)this.getValue()).getName());
        super.onSerialization(data);
        data.addProperty("level", (Number)Integer.valueOf(this.permissionLevel));
        data.addProperty("bypassesPlayerLimit", Boolean.valueOf(this.bypassesPlayerLimit));
    }
}
 
Example 8
Project: Wechat-Group   File: WxMpUserTagServiceImpl.java   View Source Code Vote up 5 votes
@Override
public WxUserTag tagCreate(String name) throws WxErrorException {
  String url = API_URL_PREFIX + "/create";
  JsonObject json = new JsonObject();
  JsonObject tagJson = new JsonObject();
  tagJson.addProperty("name", name);
  json.add("tag", tagJson);

  String responseContent = this.wxMpService.post(url, json.toString());
  return WxUserTag.fromJson(responseContent);
}
 
Example 9
Project: BaseClient   File: BanEntry.java   View Source Code Vote up 5 votes
protected void onSerialization(JsonObject data)
{
    data.addProperty("created", dateFormat.format(this.banStartDate));
    data.addProperty("source", this.bannedBy);
    data.addProperty("expires", this.banEndDate == null ? "forever" : dateFormat.format(this.banEndDate));
    data.addProperty("reason", this.reason);
}
 
Example 10
Project: BaseClient   File: UserListOpsEntry.java   View Source Code Vote up 5 votes
protected void onSerialization(JsonObject data)
{
    if (this.getValue() != null)
    {
        data.addProperty("uuid", ((GameProfile)this.getValue()).getId() == null ? "" : ((GameProfile)this.getValue()).getId().toString());
        data.addProperty("name", ((GameProfile)this.getValue()).getName());
        super.onSerialization(data);
        data.addProperty("level", (Number)Integer.valueOf(this.field_152645_a));
        data.addProperty("bypassesPlayerLimit", Boolean.valueOf(this.field_183025_b));
    }
}
 
Example 11
Project: shuffleboard   File: WidgetPaneSaver.java   View Source Code Vote up 5 votes
@Override
public JsonElement serialize(WidgetPane src, JsonSerializationContext context) {
  JsonObject object = new JsonObject();
  object.addProperty("gridSize", src.getTileSize());
  object.addProperty("hgap", src.getHgap());
  object.addProperty("vgap", src.getVgap());
  JsonObject tiles = new JsonObject();

  for (Tile<?> tile : src.getTiles()) {
    String x = GridPane.getColumnIndex(tile).toString();
    String y = GridPane.getRowIndex(tile).toString();
    String coordinate = String.join(",", x, y);

    JsonObject tileObject = new JsonObject();
    tileObject.add("size", context.serialize(tile.getSize(), TileSize.class));
    tileObject.add("content", context.serialize(tile.getContent(), tile.getContent().getClass()));

    tiles.add(coordinate, tileObject);
  }
  object.add("tiles", tiles);

  return object;
}
 
Example 12
Project: buckaroo   File: RecipeVersionSerializer.java   View Source Code Vote up 5 votes
@Override
public JsonElement serialize(
        final RecipeVersion recipeVersion, final Type type, final JsonSerializationContext context) {

    Preconditions.checkNotNull(recipeVersion);
    Preconditions.checkNotNull(type);
    Preconditions.checkNotNull(context);

    final JsonObject jsonObject = new JsonObject();

    final JsonElement sourceElement = Either.join(
        recipeVersion.source,
        context::serialize,
        context::serialize);

    jsonObject.add("source", sourceElement);

    if (recipeVersion.target.isPresent()) {
        jsonObject.addProperty("target", recipeVersion.target.get());
    }

    if (recipeVersion.dependencies.map(DependencyGroup::any).orElse(false)) {
        jsonObject.add("dependencies", context.serialize(recipeVersion.dependencies.get()));
    }

    if (recipeVersion.buckResource.isPresent()) {
        jsonObject.add("buck", context.serialize(recipeVersion.buckResource.get(), RemoteFile.class));
    }

    return jsonObject;
}
 
Example 13
Project: SuprDiscordBot   File: Channel.java   View Source Code Vote up 5 votes
/**
 * @param content Content of the message to be sent
 * @return The newly sent message.
 */
public Message sendMessage(String content)
{
	JsonObject json = new JsonObject();
	json.addProperty("content", content);
	return (Message) DiscordAPI.request("POST", "/channels/" + id + "/messages", json.toString(), new Message());
}
 
Example 14
Project: sats-core   File: MRVMGenericDefinition.java   View Source Code Vote up 5 votes
/**
 * @see GenericDefinition#shortJson()
 */
@Override
public JsonElement shortJson() {
    JsonObject json = new JsonObject();
    json.addProperty("band", band.getName());
    json.addProperty("region", region.getId());
    return json;
}
 
Example 15
Project: Cypher   File: UserTest.java   View Source Code Vote up 5 votes
@Test
public void updateFromSync() {
	JsonObject data = new JsonObject();

	data.addProperty("type", "m.presence");

	JsonObject content = new JsonObject();
	content.addProperty("presence", "offline");
	data.add("content", content);

	user.update(data);

	Assert.assertEquals("User object did not parse presence sync data", user.getPresence(), User.Presence.OFFLINE);
}
 
Example 16
Project: BaseClient   File: ChatStyle.java   View Source Code Vote up 4 votes
public JsonElement serialize(ChatStyle p_serialize_1_, Type p_serialize_2_, JsonSerializationContext p_serialize_3_)
{
    if (p_serialize_1_.isEmpty())
    {
        return null;
    }
    else
    {
        JsonObject jsonobject = new JsonObject();

        if (p_serialize_1_.bold != null)
        {
            jsonobject.addProperty("bold", p_serialize_1_.bold);
        }

        if (p_serialize_1_.italic != null)
        {
            jsonobject.addProperty("italic", p_serialize_1_.italic);
        }

        if (p_serialize_1_.underlined != null)
        {
            jsonobject.addProperty("underlined", p_serialize_1_.underlined);
        }

        if (p_serialize_1_.strikethrough != null)
        {
            jsonobject.addProperty("strikethrough", p_serialize_1_.strikethrough);
        }

        if (p_serialize_1_.obfuscated != null)
        {
            jsonobject.addProperty("obfuscated", p_serialize_1_.obfuscated);
        }

        if (p_serialize_1_.color != null)
        {
            jsonobject.add("color", p_serialize_3_.serialize(p_serialize_1_.color));
        }

        if (p_serialize_1_.insertion != null)
        {
            jsonobject.add("insertion", p_serialize_3_.serialize(p_serialize_1_.insertion));
        }

        if (p_serialize_1_.chatClickEvent != null)
        {
            JsonObject jsonobject1 = new JsonObject();
            jsonobject1.addProperty("action", p_serialize_1_.chatClickEvent.getAction().getCanonicalName());
            jsonobject1.addProperty("value", p_serialize_1_.chatClickEvent.getValue());
            jsonobject.add("clickEvent", jsonobject1);
        }

        if (p_serialize_1_.chatHoverEvent != null)
        {
            JsonObject jsonobject2 = new JsonObject();
            jsonobject2.addProperty("action", p_serialize_1_.chatHoverEvent.getAction().getCanonicalName());
            jsonobject2.add("value", p_serialize_3_.serialize(p_serialize_1_.chatHoverEvent.getValue()));
            jsonobject.add("hoverEvent", jsonobject2);
        }

        return jsonobject;
    }
}
 
Example 17
Project: CustomWorldGen   File: SetNBT.java   View Source Code Vote up 4 votes
public void serialize(JsonObject object, SetNBT functionClazz, JsonSerializationContext serializationContext)
{
    object.addProperty("tag", functionClazz.tag.toString());
}
 
Example 18
Project: iotplatform   File: MqttTransportHandler.java   View Source Code Vote up 4 votes
private void processDevicePublish(ChannelHandlerContext ctx, MqttPublishMessage mqttMsg, String topicName,
    int msgId) {
  // AdaptorToSessionActorMsg msg = null;
  int refCnt = mqttMsg.refCnt();
  int messageId = mqttMsg.variableHeader().messageId();
  log.info("[{}] refCnt: [{}], messageId: [{}]", sessionId, refCnt, messageId);
  MqttPublishMessage retainedDuplicate = mqttMsg.retainedDuplicate();
  String kafkaOutboundTopic = null;
  try {
    if (topicName.equals(DEVICE_TELEMETRY_TOPIC)) {
      // msg = adaptor.convertToActorMsg(deviceSessionCtx,
      // POST_TELEMETRY_REQUEST, mqttMsg);
      kafkaOutboundTopic = KafkaTopics.DEVICE_TELEMETRY_TOPIC;
    } else if (topicName.equals(DEVICE_ATTRIBUTES_TOPIC)) {
      kafkaOutboundTopic = KafkaTopics.DEVICE_ATTRIBUTES_TOPIC;
      // msg = adaptor.convertToActorMsg(deviceSessionCtx,
      // POST_ATTRIBUTES_REQUEST, mqttMsg);

      // MqttMessage createSubscribeResponseMessage =
      // createSubscribeResponseMessage(msgId);
      //// System.out.println(createSubscribeResponseMessage.payload());
      // ctx.writeAndFlush(createSubscribeResponseMessage);

    } else if (topicName.startsWith(DEVICE_ATTRIBUTES_REQUEST_TOPIC_PREFIX)) {
      // msg = adaptor.convertToActorMsg(deviceSessionCtx,
      // GET_ATTRIBUTES_REQUEST, mqttMsg);
      kafkaOutboundTopic = KafkaTopics.DEVICE_ATTRIBUTES_REQUEST_TOPIC_PREFIX;
      if (msgId >= 0) {
        ctx.writeAndFlush(createMqttPubAckMsg(msgId));
      }
    } else if (topicName.startsWith(DEVICE_RPC_RESPONSE_TOPIC)) {
      // msg = adaptor.convertToActorMsg(deviceSessionCtx,
      // TO_DEVICE_RPC_RESPONSE, mqttMsg);
      kafkaOutboundTopic = KafkaTopics.DEVICE_ATTRIBUTES_RESPONSE_TOPIC_PREFIX;
      if (msgId >= 0) {
        ctx.writeAndFlush(createMqttPubAckMsg(msgId));
      }
    } else if (topicName.startsWith(DEVICE_RPC_REQUESTS_TOPIC)) {
      // msg = adaptor.convertToActorMsg(deviceSessionCtx,
      // TO_SERVER_RPC_REQUEST, mqttMsg);
      kafkaOutboundTopic = KafkaTopics.DEVICE_RPC_REQUESTS_TOPIC;
      if (msgId >= 0) {
        ctx.writeAndFlush(createMqttPubAckMsg(msgId));
      }
    }
  } catch (Exception e) {
    log.warn("[{}] Failed to process publish msg [{}][{}]", sessionId, topicName, msgId, e);
  }
  if (kafkaOutboundTopic != null) {
    String payload = new String(ByteBufUtil.getBytes(retainedDuplicate.payload()));

    Set<ChannelEntity> channelEntitys = MemoryMetaPool.getChannelByTopics(topicName);
    if (channelEntitys != null) {
      for (ChannelEntity channelEntity : channelEntitys) {
        log.info("PUBLISH to ChannelEntity topic = " + topicName + " payload = " + payload);
        channelEntity.write(retainedDuplicate);
      }
    }

    Device device = deviceSessionCtx.getDevice();
    if (device != null && device.getId() != null) {
      // BasicToDeviceActorSessionMsg basicToDeviceActorSessionMsg = new
      // BasicToDeviceActorSessionMsg(
      // device, msg);
      JsonObject root = new JsonObject();
      JsonElement jsonElement = new JsonParser().parse(payload);
      root.add("d", jsonElement);
      root.addProperty("messageId", messageId);
      log.info("[{}] msg: {}", sessionId, root.toString());

      this.msgProducer.send(kafkaOutboundTopic, device.getId().toString(), root.toString());
    }
    // processor.process(basicToDeviceActorSessionMsg);
  } else {
    log.info("[{}] Closing current session due to invalid publish msg [{}][{}]", sessionId, topicName, msgId);
    ctx.close();
  }
}
 
Example 19
Project: logistimo-web-service   File: GsonUtil.java   View Source Code Vote up 4 votes
public static String updateInventoryOutputToJson(boolean status, String message,
                                                 List materialList, Vector errors,
                                                 String formattedTime, String trackingIdStr,
                                                 String localeStr, String version) {
  Gson
      gson =
      new GsonBuilder().setDateFormat(Constants.DATE_FORMAT)
          .excludeFieldsWithoutExposeAnnotation().create();
  String jsonString = null;
  Boolean hasPartialErrors = false;
  JsonObject jsonObject = new JsonObject();
  String statusCode = status ? "0" : "1";
  if (errors != null && !errors.isEmpty()) {
    hasPartialErrors = true;
    statusCode = "2";
  }
  jsonObject.addProperty(JsonTagsZ.VERSION, version);
  jsonObject.addProperty(JsonTagsZ.STATUS, statusCode);

  if (status || hasPartialErrors) {
    jsonObject.addProperty(JsonTagsZ.TIMESTAMP, formattedTime);
    jsonObject.addProperty(JsonTagsZ.TRACKING_ID, trackingIdStr);
    if (materialList != null && !materialList.isEmpty()) {
      String materialString = gson.toJson(materialList);
      JsonElement mElement = gson.fromJson(materialString, JsonElement.class);
      jsonObject.add(JsonTagsZ.MATERIALS, mElement);
    }
    if (hasPartialErrors) {
      String errorString = gson.toJson(errors);
      if (errorString != null && !errorString.isEmpty()) {
        JsonElement errorElement = gson.fromJson(errorString, JsonElement.class);
        jsonObject.add(JsonTagsZ.ERRORS, errorElement);
      }
    }

  } else {
    if (message != null) {
      jsonObject.addProperty(JsonTagsZ.MESSAGE, message);
    }
  }
  if (jsonObject != null) {
    jsonString = gson.toJson(jsonObject);
  }
  return jsonString;

}
 
Example 20
Project: CustomWorldGen   File: KilledByPlayer.java   View Source Code Vote up 4 votes
public void serialize(JsonObject json, KilledByPlayer value, JsonSerializationContext context)
{
    json.addProperty("inverse", Boolean.valueOf(value.inverse));
}