Java Code Examples for com.google.gson.JsonParser#parseString()

The following examples show how to use com.google.gson.JsonParser#parseString() . 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: EventTypeExtractorImpl.java    From java-slack-sdk with MIT License 6 votes vote down vote up
private static String extractFieldUnderEvent(String json, String fieldName) {
    try {
        JsonElement root = JsonParser.parseString(json);
        if (root != null && root.isJsonObject() && root.getAsJsonObject().has("event")) {
            JsonElement event = root.getAsJsonObject().get("event");
            if (event.isJsonObject() && event.getAsJsonObject().has(fieldName)) {
                JsonElement eventType = event.getAsJsonObject().get(fieldName);
                if (eventType.isJsonPrimitive()) {
                    return eventType.getAsString();
                }
            }
        }
    } catch (JsonSyntaxException e) {
        log.debug("Failed to parse {} as a JSON data", json, e);
    }
    return "";
}
 
Example 2
Source File: JsonElementReaderTest.java    From gson with Apache License 2.0 6 votes vote down vote up
public void testObject() throws IOException {
  JsonElement element = JsonParser.parseString("{\"A\": 1, \"B\": 2}");
  JsonTreeReader reader = new JsonTreeReader(element);
  assertEquals(JsonToken.BEGIN_OBJECT, reader.peek());
  reader.beginObject();
  assertEquals(JsonToken.NAME, reader.peek());
  assertEquals("A", reader.nextName());
  assertEquals(JsonToken.NUMBER, reader.peek());
  assertEquals(1, reader.nextInt());
  assertEquals(JsonToken.NAME, reader.peek());
  assertEquals("B", reader.nextName());
  assertEquals(JsonToken.NUMBER, reader.peek());
  assertEquals(2, reader.nextInt());
  assertEquals(JsonToken.END_OBJECT, reader.peek());
  reader.endObject();
  assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
 
Example 3
Source File: JsonElementReaderTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testArray() throws IOException {
  JsonElement element = JsonParser.parseString("[1, 2, 3]");
  JsonTreeReader reader = new JsonTreeReader(element);
  assertEquals(JsonToken.BEGIN_ARRAY, reader.peek());
  reader.beginArray();
  assertEquals(JsonToken.NUMBER, reader.peek());
  assertEquals(1, reader.nextInt());
  assertEquals(JsonToken.NUMBER, reader.peek());
  assertEquals(2, reader.nextInt());
  assertEquals(JsonToken.NUMBER, reader.peek());
  assertEquals(3, reader.nextInt());
  assertEquals(JsonToken.END_ARRAY, reader.peek());
  reader.endArray();
  assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
 
Example 4
Source File: JsonElementReaderTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testStrings() throws IOException {
  JsonElement element = JsonParser.parseString("[\"A\",\"B\"]");
  JsonTreeReader reader = new JsonTreeReader(element);
  reader.beginArray();
  assertEquals("A", reader.nextString());
  assertEquals("B", reader.nextString());
  reader.endArray();
}
 
Example 5
Source File: JsonElementReaderTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testNulls() throws IOException {
  JsonElement element = JsonParser.parseString("[null,null]");
  JsonTreeReader reader = new JsonTreeReader(element);
  reader.beginArray();
  reader.nextNull();
  reader.nextNull();
  reader.endArray();
}
 
Example 6
Source File: JsonElementReaderTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testBooleans() throws IOException {
  JsonElement element = JsonParser.parseString("[true, false]");
  JsonTreeReader reader = new JsonTreeReader(element);
  reader.beginArray();
  assertEquals(true, reader.nextBoolean());
  assertEquals(false, reader.nextBoolean());
  reader.endArray();
}
 
Example 7
Source File: JsonElementReaderTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testStringsFromNumbers() throws IOException {
  JsonElement element = JsonParser.parseString("[1]");
  JsonTreeReader reader = new JsonTreeReader(element);
  reader.beginArray();
  assertEquals("1", reader.nextString());
  reader.endArray();
}
 
Example 8
Source File: JsonElementReaderTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testNumbersFromStrings() throws IOException {
  JsonElement element = JsonParser.parseString("[\"1\", \"2\", \"3\"]");
  JsonTreeReader reader = new JsonTreeReader(element);
  reader.beginArray();
  assertEquals(1, reader.nextInt());
  assertEquals(2L, reader.nextLong());
  assertEquals(3.0, reader.nextDouble());
  reader.endArray();
}
 
Example 9
Source File: JsonElementReaderTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testNestedArrays() throws IOException {
  JsonElement element = JsonParser.parseString("[[],[[]]]");
  JsonTreeReader reader = new JsonTreeReader(element);
  reader.beginArray();
  reader.beginArray();
  reader.endArray();
  reader.beginArray();
  reader.beginArray();
  reader.endArray();
  reader.endArray();
  reader.endArray();
}
 
Example 10
Source File: MapTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testMapNamePromotionWithJsonElementReader() {
  String json = "{'2.3':'a'}";
  Map<Double, String> map = new LinkedHashMap<Double, String>();
  map.put(2.3, "a");
  JsonElement tree = JsonParser.parseString(json);
  assertEquals(map, gson.fromJson(tree, new TypeToken<Map<Double, String>>() {}.getType()));
}
 
Example 11
Source File: TestUtils.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
public static boolean isValid(String json) {
    try {
        JsonParser.parseString(json);
        return true;
    } catch (JsonSyntaxException jse) {
        return false;
    }
}
 
Example 12
Source File: ResponsePrettyPrintingListener.java    From java-slack-sdk with MIT License 5 votes vote down vote up
@Override
public void accept(State state) {
    SlackConfig config = state.getConfig();
    String body = state.getParsedResponseBody();
    if (config.isPrettyResponseLoggingEnabled() && body != null && body.trim().startsWith("{")) {
        JsonElement jsonObj = JsonParser.parseString(body);
        String prettifiedJson = GsonFactory.createSnakeCase(config).toJson(jsonObj);

        JSON_RESPONSE_LOGGER.debug("--- Pretty printing the response ---\n" +
                prettifiedJson + "\n" +
                "-----------------------------------------");
    }
}
 
Example 13
Source File: JsonElementReaderTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testEarlyClose() throws IOException {
  JsonElement element = JsonParser.parseString("[1, 2, 3]");
  JsonTreeReader reader = new JsonTreeReader(element);
  reader.beginArray();
  reader.close();
  try {
    reader.peek();
    fail();
  } catch (IllegalStateException expected) {
  }
}
 
Example 14
Source File: GitHubJsonStoreTest.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test(dataProvider = "inputStores")
public void testGetAndModifyJsonString(String storeContent, String image, String tag, String expectedOutput) throws Exception {
    GitHubUtil gitHubUtil = mock(GitHubUtil.class);
    JsonElement json = JsonParser.parseString(storeContent);

    String output = new GitHubJsonStore(gitHubUtil, "test").getAndModifyJsonString(json, image, tag);
    assertEquals(output, expectedOutput);
}
 
Example 15
Source File: GitHubUtil.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public int createPullReq(GHRepository origRepo, String branch,
                                 GHRepository forkRepo, String title, String body) throws InterruptedException {
        log.info("Creating Pull Request on {} from {}...", origRepo.getFullName(), forkRepo.getFullName());
        //TODO: if no commits, pull request will fail, but this doesn't handle that.
        try {
            GHPullRequest pullRequest = origRepo.createPullRequest(title, forkRepo.getOwnerName() + ":" + branch,
                    origRepo.getDefaultBranch(), body);
//            origRepo.createPullRequest("Update base image in Dockerfile", forkRepo.getOwnerName() + ":" + branch,
//                    origRepo.getDefaultBranch(), "Automatic Dockerfile Image Updater. Please merge.");
            log.info("A pull request has been created at {}", pullRequest.getHtmlUrl());
            return 0;
        } catch (IOException e) {
            log.warn("Handling error with pull request creation... {}", e.getMessage());
            JsonElement root = JsonParser.parseString(e.getMessage());
            JsonArray errorJson = root.getAsJsonObject().get("errors").getAsJsonArray();
            String error = errorJson.get(0).getAsJsonObject().get("message").getAsString();
            log.info("error: {}", error);
            if (error.startsWith("A pull request already exists")) {
                log.info("NOTE: {} New commits may have been added to the pull request.", error);
                return 0;
            } else if (error.startsWith("No commits between")) {
                log.warn("NOTE: {} Pull request was not created.", error);
                return 1;
            } else {
                // TODO: THIS WILL LOOP FOREVVEEEEEERRRR
                log.warn("An error occurred in pull request: {} Trying again...", error);
                waitFor(TimeUnit.SECONDS.toMillis(3));
                return -1;
            }
        }
    }
 
Example 16
Source File: JsonElementReaderTest.java    From gson with Apache License 2.0 4 votes vote down vote up
public void testEmptyObject() throws IOException {
  JsonElement element = JsonParser.parseString("{}");
  JsonTreeReader reader = new JsonTreeReader(element);
  reader.beginObject();
  reader.endObject();
}
 
Example 17
Source File: JsonElementReaderTest.java    From gson with Apache License 2.0 4 votes vote down vote up
public void testEmptyArray() throws IOException {
  JsonElement element = JsonParser.parseString("[]");
  JsonTreeReader reader = new JsonTreeReader(element);
  reader.beginArray();
  reader.endArray();
}
 
Example 18
Source File: ArraySplitOperationTest.java    From bender with Apache License 2.0 4 votes vote down vote up
@Test
public void testArraySplitWithFieldsToKeep() throws IOException {
  TestContext t = new TestContext();
  t.setFunctionName("foo");
  LambdaContext lctx = new LambdaContext(t);

  JsonElement input = JsonParser.parseString(getResourceString("array_input_kinesis_format.json"));
  GenericJsonEvent devent = new GenericJsonEvent(input.getAsJsonObject());
  List<String> fieldsToKeep = Arrays.asList("owner", "logGroup", "logStream");
  ArraySplitOperation operation = new ArraySplitOperation("$.logEvents", fieldsToKeep);

  InternalEvent ievent = new InternalEvent("", lctx, 123);
  ievent.setEventObj(devent);
  ievent.setEventTime(124);
  List<InternalEvent> events = operation.perform(ievent);

  assertEquals(4, events.size());
  JsonElement actual = JsonParser.parseString(events.get(0).getEventString());
  assertTrue(actual.getAsJsonObject().has("owner"));
  assertTrue(actual.getAsJsonObject().has("logGroup"));
  assertTrue(actual.getAsJsonObject().has("logStream"));
  assertTrue(actual.getAsJsonObject().has("id"));
  assertTrue(actual.getAsJsonObject().has("message"));
  assertTrue(actual.getAsJsonObject().has("timestamp"));

  actual = JsonParser.parseString(events.get(1).getEventString());
  assertTrue(actual.getAsJsonObject().has("owner"));
  assertTrue(actual.getAsJsonObject().has("logGroup"));
  assertTrue(actual.getAsJsonObject().has("logStream"));
  assertTrue(actual.getAsJsonObject().has("id"));
  assertTrue(actual.getAsJsonObject().has("message"));
  assertTrue(actual.getAsJsonObject().has("timestamp"));

  actual = JsonParser.parseString(events.get(2).getEventString());
  assertTrue(actual.getAsJsonObject().has("owner"));
  assertTrue(actual.getAsJsonObject().has("logGroup"));
  assertTrue(actual.getAsJsonObject().has("logStream"));
  assertTrue(actual.getAsJsonObject().has("id"));
  assertTrue(actual.getAsJsonObject().has("message"));
  assertTrue(actual.getAsJsonObject().has("timestamp"));

  actual = JsonParser.parseString(events.get(3).getEventString());
  assertTrue(actual.getAsJsonObject().has("owner"));
  assertTrue(actual.getAsJsonObject().has("logGroup"));
  assertTrue(actual.getAsJsonObject().has("logStream"));
  assertTrue(actual.getAsJsonObject().has("id"));
  assertTrue(actual.getAsJsonObject().has("message"));
  assertTrue(actual.getAsJsonObject().has("timestamp"));
}
 
Example 19
Source File: JsonUtils.java    From headlong with Apache License 2.0 4 votes vote down vote up
public static JsonElement parse(String json) {
    return JsonParser.parseString(json);
}
 
Example 20
Source File: ReportState.java    From smart-home-java with Apache License 2.0 3 votes vote down vote up
/**
 * Creates and completes a ReportStateAndNotification request
 *
 * @param actionsApp The SmartHomeApp instance to use to make the gRPC request
 * @param userId The agent user ID
 * @param deviceId The device ID
 * @param states A Map of state keys and their values for the provided device ID
 */
public static void makeRequest(
    SmartHomeApp actionsApp, String userId, String deviceId, Map<String, Object> states) {
  // Convert a Map of states to a JsonObject
  JsonObject jsonStates = (JsonObject) JsonParser.parseString(new Gson().toJson(states));
  ReportState.makeRequest(actionsApp, userId, deviceId, jsonStates);
}