com.google.gson.JsonPrimitive Java Examples

The following examples show how to use com.google.gson.JsonPrimitive. 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: VirtualChestPlaceholderManager.java    From VirtualChest with GNU Lesser General Public License v3.0 6 votes vote down vote up
public String parseJavaScriptLiteral(String text, String functionIdentifier)
{
    StringBuilder builder = new StringBuilder();
    Matcher matcher = PLACEHOLDER_PATTERN.matcher(text);
    int lastIndex = 0;
    while (matcher.find())
    {
        String matched = new JsonPrimitive(text.substring(matcher.start() + 1, matcher.end() - 1)).toString();
        builder.append(text, lastIndex, matcher.start()).append(functionIdentifier);
        builder.append("(").append(matched).append(")");
        lastIndex = matcher.end();
    }
    if (lastIndex < text.length())
    {
        builder.append(text.substring(lastIndex));
    }
    return builder.toString();
}
 
Example #2
Source File: NumberValue.java    From ClientBase with MIT License 6 votes vote down vote up
@Override
public void fromJsonObject(@NotNull JsonObject obj) {
    if (obj.has(getName())) {
        JsonElement element = obj.get(getName());

        if (element instanceof JsonPrimitive && ((JsonPrimitive) element).isNumber()) {

            if (getObject() instanceof Integer) {
                setObject((T) Integer.valueOf(obj.get(getName()).getAsNumber().intValue()));
            }
            if (getObject() instanceof Long) {
                setObject((T) Long.valueOf(obj.get(getName()).getAsNumber().longValue()));
            }
            if (getObject() instanceof Float) {
                setObject((T) Float.valueOf(obj.get(getName()).getAsNumber().floatValue()));
            }
            if (getObject() instanceof Double) {
                setObject((T) Double.valueOf(obj.get(getName()).getAsNumber().doubleValue()));
            }
        } else {
            throw new IllegalArgumentException("Entry '" + getName() + "' is not valid");
        }
    } else {
        throw new IllegalArgumentException("Object does not have '" + getName() + "'");
    }
}
 
Example #3
Source File: JsonOutputTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToConvertACommand() {
  SessionId sessionId = new SessionId("some id");
  String commandName = "some command";
  Map<String, Object> parameters = new HashMap<>();
  parameters.put("param1", "value1");
  parameters.put("param2", "value2");
  Command command = new Command(sessionId, commandName, parameters);

  String json = convert(command);

  JsonObject converted = new JsonParser().parse(json).getAsJsonObject();

  assertThat(converted.has("sessionId")).isTrue();
  JsonPrimitive sid = converted.get("sessionId").getAsJsonPrimitive();
  assertThat(sid.getAsString()).isEqualTo(sessionId.toString());

  assertThat(commandName).isEqualTo(converted.get("name").getAsString());

  assertThat(converted.has("parameters")).isTrue();
  JsonObject pars = converted.get("parameters").getAsJsonObject();
  assertThat(pars.entrySet()).hasSize(2);
  assertThat(pars.get("param1").getAsString()).isEqualTo(parameters.get("param1"));
  assertThat(pars.get("param2").getAsString()).isEqualTo(parameters.get("param2"));
}
 
Example #4
Source File: JsonAdapterAnnotationOnClassesTest.java    From gson with Apache License 2.0 6 votes vote down vote up
/**
 * The serializer overrides field adapter, but for deserializer the fieldAdapter is used.
 */
public void testRegisteredSerializerOverridesJsonAdapter() {
  JsonSerializer<A> serializer = new JsonSerializer<A>() {
    public JsonElement serialize(A src, Type typeOfSrc,
        JsonSerializationContext context) {
      return new JsonPrimitive("registeredSerializer");
    }
  };
  Gson gson = new GsonBuilder()
    .registerTypeAdapter(A.class, serializer)
    .create();
  String json = gson.toJson(new A("abcd"));
  assertEquals("\"registeredSerializer\"", json);
  A target = gson.fromJson("abcd", A.class);
  assertEquals("jsonAdapter", target.value);
}
 
Example #5
Source File: AndroidOperation.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP,
        description = "Test Android device lock operation for invalid device id.")
public void testLockWithInvalidDeviceId() throws Exception {
    JsonObject operationData = PayloadGenerator
            .getJsonPayload(Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME,
                    Constants.AndroidOperations.LOCK_OPERATION);
    JsonArray deviceIds = new JsonArray();
    JsonPrimitive deviceID = new JsonPrimitive(Constants.NUMBER_NOT_EQUAL_TO_DEVICE_ID);
    deviceIds.add(deviceID);
    operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds);

    try {
        client.post(Constants.AndroidOperations.ANDROID_DEVICE_MGT_API + Constants.AndroidOperations.LOCK_ENDPOINT,
                operationData.toString());
    } catch (Exception e) {
        Assert.assertTrue(e.getMessage().contains("HTTP response code: 400"));
    }
}
 
Example #6
Source File: AndroidOperation.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP,
        description = "Test Android encrypt operation for invalid device id")
public void testEncryptWithInvalidDeviceId() throws Exception {
    JsonObject operationData = PayloadGenerator
            .getJsonPayload(Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME,
                    Constants.AndroidOperations.ENCRYPT_OPERATION);
    JsonArray deviceIds = new JsonArray();
    JsonPrimitive deviceID = new JsonPrimitive(Constants.NUMBER_NOT_EQUAL_TO_DEVICE_ID);
    deviceIds.add(deviceID);
    operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds);
    try {
        client.post(
                Constants.AndroidOperations.ANDROID_DEVICE_MGT_API + Constants.AndroidOperations.ENCRYPT_ENDPOINT,
                operationData.toString());
    } catch (Exception e) {
        Assert.assertTrue(e.getMessage().contains("HTTP response code: 400"));
    }
}
 
Example #7
Source File: Metrics.java    From bStats-Metrics with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected JsonObject getChartData() throws Exception {
    JsonObject data = new JsonObject();
    JsonObject values = new JsonObject();
    Map<String, Integer> map = callable.call();
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        JsonArray categoryValues = new JsonArray();
        categoryValues.add(new JsonPrimitive(entry.getValue()));
        values.add(entry.getKey(), categoryValues);
    }
    data.add("values", values);
    return data;
}
 
Example #8
Source File: Metrics2.java    From bStats-Metrics with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected JsonObject getChartData() throws Exception {
    JsonObject data = new JsonObject();
    JsonObject values = new JsonObject();
    Map<String, Integer> map = callable.call();
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        JsonArray categoryValues = new JsonArray();
        categoryValues.add(new JsonPrimitive(entry.getValue()));
        values.add(entry.getKey(), categoryValues);
    }
    data.add("values", values);
    return data;
}
 
Example #9
Source File: main.java    From graphify with Apache License 2.0 6 votes vote down vote up
private static void trainOnText(String[] text, String[] label) {
    List<String> labelSet = new ArrayList<>();
    List<String> textSet = new ArrayList<>();

    Collections.addAll(labelSet, label);
    Collections.addAll(textSet, text);

    JsonArray labelArray = new JsonArray();
    JsonArray textArray = new JsonArray();

    labelSet.forEach((s) -> labelArray.add(new JsonPrimitive(s)));
    textSet.forEach((s) -> textArray.add(new JsonPrimitive(s)));

    JsonObject jsonParam = new JsonObject();
    jsonParam.add("text", textArray);
    jsonParam.add("label", labelArray);
    jsonParam.add("focus", new JsonPrimitive(2));

    String jsonPayload = new Gson().toJson(jsonParam);

    System.out.println(executePost("http://localhost:7474/service/graphify/training", jsonPayload));
}
 
Example #10
Source File: OperationRequestGsonAdaptorRobotTest.java    From swellrt with Apache License 2.0 6 votes vote down vote up
public void testDeserialize() throws Exception {
  String operation = "{'id':'op1','method':'wavelet.setTitle','params':{" +
      "'waveId':'1','waveletId':'2','waveletTitle':'Title','unknown':'value'}}";
  JsonElement jsonElement = new JsonParser().parse(operation);

  JsonDeserializationContext mockContext = mock(JsonDeserializationContext.class);
  when(mockContext.deserialize(any(JsonElement.class), eq(String.class))).thenAnswer(
      new Answer<String>() {
        public String answer(InvocationOnMock invocation) {
          return ((JsonPrimitive) (invocation.getArguments()[0])).getAsString();
        }
      });

  OperationRequestGsonAdaptor adaptor = new OperationRequestGsonAdaptor();
  OperationRequest result = adaptor.deserialize(jsonElement, null, mockContext);
  assertEquals("op1", result.getId());
  assertEquals("wavelet.setTitle", result.getMethod());
  assertEquals("1", result.getWaveId());
  assertEquals("2", result.getWaveletId());
  assertNull(result.getBlipId());
  assertEquals(3, result.getParams().size());
  assertEquals("Title", result.getParameter(ParamsProperty.WAVELET_TITLE));
}
 
Example #11
Source File: AbstractPluginMessagingForwardingSink.java    From NuVotifier with GNU General Public License v3.0 6 votes vote down vote up
public void handlePluginMessage(byte[] message) {
    String strMessage = new String(message, StandardCharsets.UTF_8);
    try (CharArrayReader reader = new CharArrayReader(strMessage.toCharArray())) {
        JsonReader r = new JsonReader(reader);
        r.setLenient(true);
        while (r.peek() != JsonToken.END_DOCUMENT) {
            r.beginObject();
            JsonObject o = new JsonObject();

            while (r.hasNext()) {
                String name = r.nextName();
                if (r.peek() == JsonToken.NUMBER)
                    o.add(name, new JsonPrimitive(r.nextLong()));
                else
                    o.add(name, new JsonPrimitive(r.nextString()));
            }
            r.endObject();

            Vote v = new Vote(o);
            listener.onForward(v);
        }
    } catch (IOException e) {
        e.printStackTrace(); // Should never happen.
    }
}
 
Example #12
Source File: GsonTypeSerializer.java    From helper with MIT License 6 votes vote down vote up
@Override
public void serialize(TypeToken<?> type, JsonElement from, ConfigurationNode to) throws ObjectMappingException {
    if (from.isJsonPrimitive()) {
        JsonPrimitive primitive = from.getAsJsonPrimitive();
        to.setValue(GsonConverters.IMMUTABLE.unwarpPrimitive(primitive));
    } else if (from.isJsonNull()) {
        to.setValue(null);
    } else if (from.isJsonArray()) {
        JsonArray array = from.getAsJsonArray();
        // ensure 'to' is a list node
        to.setValue(ImmutableList.of());
        for (JsonElement element : array) {
            serialize(TYPE, element, to.getAppendedNode());
        }
    } else if (from.isJsonObject()) {
        JsonObject object = from.getAsJsonObject();
        // ensure 'to' is a map node
        to.setValue(ImmutableMap.of());
        for (Map.Entry<String, JsonElement> ent : object.entrySet()) {
            serialize(TYPE, ent.getValue(), to.getNode(ent.getKey()));
        }
    } else {
        throw new ObjectMappingException("Unknown element type: " + from.getClass());
    }
}
 
Example #13
Source File: ReplicatorDocument.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
private String getEndpointUrl(JsonElement element) {
    if (element == null) {
        return null;
    }
    JsonPrimitive urlString = null;
    if (element.isJsonPrimitive()) {
        urlString = element.getAsJsonPrimitive();
    } else {
        JsonObject replicatorEndpointObject = element.getAsJsonObject();
        urlString = replicatorEndpointObject.getAsJsonPrimitive("url");
    }
    if (urlString == null) {
        return null;
    }
    return urlString.getAsString();
}
 
Example #14
Source File: PublicKeyCredentialDescriptor.java    From webauthndemo with Apache License 2.0 6 votes vote down vote up
/**
 * @return Encoded JsonObject representation of PublicKeyCredentialDescriptor
 */
public JsonObject getJsonObject() {
  JsonObject result = new JsonObject();
  result.addProperty("type", type.toString());

  result.addProperty("id", BaseEncoding.base64().encode(id));
  JsonArray transports = new JsonArray();
  if (this.transports != null) {
    for (AuthenticatorTransport t : this.transports) {
      JsonPrimitive element = new JsonPrimitive(t.toString());
      transports.add(element);
    }
    if (transports.size() > 0) {
      result.add("transports", transports);
    }
  }

  return result;
}
 
Example #15
Source File: JsonUtils.java    From StatsAgg with Apache License 2.0 6 votes vote down vote up
public static String getStringFieldFromJsonObject(JsonObject jsonObject, String fieldName) {
    
    if (jsonObject == null) {
        return null;
    }
    
    String returnString = null;
    
    try {
        JsonElement jsonElement = jsonObject.get(fieldName);
        
        if (jsonElement != null) {
            JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
            returnString = jsonPrimitive.getAsString();
        }
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));    
    }

    return returnString;
}
 
Example #16
Source File: KcaBattle.java    From kcanotify with GNU General Public License v3.0 6 votes vote down vote up
public static int checkHeavyDamagedExist() {
    int status = HD_NONE;
    for (int i = 0; i < friendMaxHps.size(); i++) {
        if (!checkhdmgflag[i]) continue;
        if (friendNowHps.get(i).getAsInt() * 4 <= friendMaxHps.get(i).getAsInt()
                && !escapelist.contains(new JsonPrimitive(i + 1))) {
            if (dameconflag[i]) {
                status = Math.max(status, HD_DAMECON);
            } else {
                status = Math.max(status, HD_DANGER);
                if (status == HD_DANGER) {
                    return status;
                }
            }
        }
    }
    return status;
}
 
Example #17
Source File: WxCpServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void userDelete(String[] userids) throws WxErrorException {
  String url = "https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete";
  JsonObject jsonObject = new JsonObject();
  JsonArray jsonArray = new JsonArray();
  for (int i = 0; i < userids.length; i++) {
    jsonArray.add(new JsonPrimitive(userids[i]));
  }
  jsonObject.add("useridlist", jsonArray);
  post(url, jsonObject.toString());
}
 
Example #18
Source File: JavaProtocolMessageUtils.java    From swellrt with Apache License 2.0 5 votes vote down vote up
private JsonMessageWrapper(int seqno, String type, JsonObject message) {
  this.jso = new JsonObject();
  jso.add("sequenceNumber", new JsonPrimitive(seqno));
  jso.add("messageType", new JsonPrimitive(type));
  jso.add("message", message);

}
 
Example #19
Source File: JsonTreeReader.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public int nextInt()
{
    JsonToken jsontoken = peek();
    if (jsontoken != JsonToken.NUMBER && jsontoken != JsonToken.STRING)
    {
        throw new IllegalStateException((new StringBuilder()).append("Expected ").append(JsonToken.NUMBER).append(" but was ").append(jsontoken).toString());
    } else
    {
        int i = ((JsonPrimitive)a()).getAsInt();
        b();
        return i;
    }
}
 
Example #20
Source File: MonteCarloTestCase.java    From headlong with Apache License 2.0 5 votes vote down vote up
JsonElement toJsonElement(Gson gson, String name, JsonPrimitive version) {

        Function f = Function.parse(name + this.function.getParamTypes().canonicalType); // this.function;

        ByteBuffer abi = f.encodeCall(this.argsTuple);

        JsonObject jsonObject = new JsonObject();
        jsonObject.add("name", new JsonPrimitive(name));
        jsonObject.add("types", Serializer.serializeTypes(f.getParamTypes(), gson));
        jsonObject.add("values", Serializer.serializeValues(this.argsTuple, gson));
        jsonObject.add("result", new JsonPrimitive("0x" + Strings.encode(abi)));
        jsonObject.add("version", version);

        return jsonObject;
    }
 
Example #21
Source File: GsonFactory.java    From dialogflow-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public MessageType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    throws JsonParseException {
  JsonPrimitive jsonValue = json.getAsJsonPrimitive();
  MessageType result = null;
  if (jsonValue.isNumber()) {
    result = MessageType.fromCode(jsonValue.getAsInt());
  } else {
    result = MessageType.fromName(jsonValue.getAsString());
  }
  if (result == null) {
    throw new JsonParseException(String.format("Unexpected message type value: %s", jsonValue));
  }
  return result;
}
 
Example #22
Source File: OAuthStoreHandlerImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
public StorageFacade(Storage<String> storage) {
    this.storage = storage;
    // Add adapters for LocalDateTime
    gson = new GsonBuilder()
            .registerTypeAdapter(LocalDateTime.class,
                    (JsonDeserializer<LocalDateTime>) (json, typeOfT, context) -> LocalDateTime
                            .parse(json.getAsString()))
            .registerTypeAdapter(LocalDateTime.class,
                    (JsonSerializer<LocalDateTime>) (date, type,
                            jsonSerializationContext) -> new JsonPrimitive(date.toString()))
            .setPrettyPrinting().create();
}
 
Example #23
Source File: GoogleServicesTask.java    From play-services-plugins with Apache License 2.0 5 votes vote down vote up
/**
 * find an item in the "client" array that match the package name of the app
 *
 * @param jsonObject the root json object.
 * @return a JsonObject representing the client entry or null if no match is found.
 */
private JsonObject getClientForPackageName(JsonObject jsonObject) {
  JsonArray array = jsonObject.getAsJsonArray("client");
  if (array != null) {
    final int count = array.size();
    for (int i = 0; i < count; i++) {
      JsonElement clientElement = array.get(i);
      if (clientElement == null || !clientElement.isJsonObject()) {
        continue;
      }

      JsonObject clientObject = clientElement.getAsJsonObject();

      JsonObject clientInfo = clientObject.getAsJsonObject("client_info");
      if (clientInfo == null) continue;

      JsonObject androidClientInfo = clientInfo.getAsJsonObject("android_client_info");
      if (androidClientInfo == null) continue;

      JsonPrimitive clientPackageName = androidClientInfo.getAsJsonPrimitive("package_name");
      if (clientPackageName == null) continue;

      if (getPackageName().equals(clientPackageName.getAsString())) {
        return clientObject;
      }
    }
  }

  return null;
}
 
Example #24
Source File: CommonUtils.java    From AngularBeans with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns JsonPrimitive with base64 javascript pattern
 * 
 * @param type
 *           Type of data
 * @param bytes
 *           array of bytes to convert
 * @return String json element in base64 javascript pattern
 */
public static JsonPrimitive getBase64Json(String type, byte[] bytes) {
   if (bytes != null && bytes.length > 0) {
      if (type == null || type.trim().length() == 0) {
         type = NGBase64.FORM_DATA_TYPE;
      }

      try {
         return new JsonPrimitive(DATA_MARK + type + BASE64_MARK + DatatypeConverter.printBase64Binary(bytes).trim()); // Base64.getEncoder().encodeToString(bytes).trim());(Java8)
      }
      catch (Exception e) {}

   }
   return null;
}
 
Example #25
Source File: gson_common_serializer.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
@Override
public JsonElement serialize(Date src,
                             Type typeOfSrc,
                             JsonSerializationContext context) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    String strResult = simpleDateFormat.format(src);

    return new JsonPrimitive(strResult);
}
 
Example #26
Source File: CommonUtils.java    From AngularBeans with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static JsonElement parse(String message) {

      if (!message.startsWith("{")) {
         return new JsonPrimitive(message);
      }
      JsonParser parser = new JsonParser();
      return parser.parse(message);
   }
 
Example #27
Source File: CodeActionResponseAdapter.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
	Predicate<JsonElement> leftChecker = new PropertyChecker("command", JsonPrimitive.class);
	Predicate<JsonElement> rightChecker = new PropertyChecker("edit").or(new PropertyChecker("command", JsonObject.class));
	TypeAdapter<Either<Command, CodeAction>> elementTypeAdapter = new EitherTypeAdapter<>(gson,
			ELEMENT_TYPE, leftChecker, rightChecker);
	return (TypeAdapter<T>) new CollectionTypeAdapter<>(gson, ELEMENT_TYPE.getType(), elementTypeAdapter, ArrayList::new);
}
 
Example #28
Source File: RomJsonConverterTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Test
public void integerListConversion() {

  JsonArray array = new JsonArray();
  array.add(new JsonPrimitive(1));
  array.add(new JsonPrimitive(2));
  array.add(new JsonPrimitive(3));

  List<Integer> list = JsonUtils.fromJson(array, new TypeToken<List<Integer>>() {
  }.getType());

  assertEquals(list.get(0), (Integer) 1);
  assertEquals(list.get(1), (Integer) 2);
  assertEquals(list.get(2), (Integer) 3);
}
 
Example #29
Source File: DefaultTypeAdaptersTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testJsonObjectDeserialization() {
  JsonObject object = new JsonObject();
  object.add("foo", new JsonPrimitive(1));
  object.add("bar", new JsonPrimitive(2));

  String json = "{\"foo\":1,\"bar\":2}";
  JsonElement actual = gson.fromJson(json, JsonElement.class);
  assertEquals(object, actual);

  JsonObject actualObj = gson.fromJson(json, JsonObject.class);
  assertEquals(object, actualObj);
}
 
Example #30
Source File: SteamStorefront.java    From async-gamequery-lib with MIT License 5 votes vote down vote up
public CompletableFuture<StoreAppDetails> getAppDetails(int appId, String countryCode, String language) {
    CompletableFuture<JsonObject> json = sendRequest(new GetAppDetails(VERSION_1, appId, countryCode, language));
    return json.thenApply(root -> {
        JsonObject appObject = root.getAsJsonObject(String.valueOf(appId));
        JsonPrimitive success = appObject.getAsJsonPrimitive("success");
        if (success != null && success.getAsBoolean()) {
            JsonObject appData = appObject.getAsJsonObject("data");
            return fromJson(appData, StoreAppDetails.class);
        }
        return null;
    });
}