Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#readTree()
The following examples show how to use
com.fasterxml.jackson.databind.ObjectMapper#readTree() .
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: MutableProfileTest.java From glowroot with Apache License 2.0 | 6 votes |
@SuppressWarnings("unused") private static void prettyPrint(String json) throws IOException { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(json); CustomPrettyPrinter prettyPrinter = new CustomPrettyPrinter(); prettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE); StringBuilder sb = new StringBuilder(); JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb)) .setPrettyPrinter(prettyPrinter); jg.writeTree(node); jg.close(); System.out.println(sb.toString().replace("\"", "\\\"").replace(DefaultIndenter.SYS_LF, "\"" + DefaultIndenter.SYS_LF + " + \"")); }
Example 2
Source File: ElasticBaseTestQuery.java From dremio-oss with Apache License 2.0 | 6 votes |
public static void compareJson(String expected, String actual) throws IOException { if(ElasticsearchCluster.USE_EXTERNAL_ES5){ // ignore json comparison for now return; } ObjectMapper m = new ObjectMapper(); JsonNode expectedRootNode = m.readTree(expected); JsonNode actualRootNode = m.readTree(actual); if (!expectedRootNode.equals(actualRootNode)) { ObjectWriter writer = m.writerWithDefaultPrettyPrinter(); String message = String.format("Comparison between JSON values failed.\nExpected:\n%s\nActual:\n%s", expected, actual); // assertEquals gives a better diff assertEquals(message, writer.writeValueAsString(expectedRootNode), writer.writeValueAsString(actualRootNode)); throw new RuntimeException(message); } }
Example 3
Source File: OrderStatusUpdateProtocol.java From order-charge-notify with Apache License 2.0 | 6 votes |
@Override public void decode(String msg) { Preconditions.checkNotNull(msg); ObjectMapper mapper = new ObjectMapper(); try { JsonNode root = mapper.readTree(msg); // header this.setVersion(root.get("header").get("version").asText()); this.setTopicName(root.get("header").get("topicName").asText()); // body this.setPurseId(root.get("body").get("purseId").asText()); this.setMerchantName(root.get("body").get("merchantName").asText()); this.setChargeMoney(root.get("body").get("chargeMoney").asText()); this.setOrderId(root.get("body").get("orderId").asText()); this.setEventType(root.get("body").get("eventType").asText()); } catch (IOException e) { throw new RuntimeException("OrderStatusUpdateProtocol消息反序列化异常", e); } }
Example 4
Source File: ConfigUtilsAirOptionsTests.java From vscode-as3mxml with Apache License 2.0 | 6 votes |
@Test void testOutputWithBaseOnly() throws IOException { String baseValue = "bin/Base.air"; ObjectMapper mapper = new ObjectMapper(); JsonNode baseConfigData = mapper.readTree( "{" + "\"airOptions\": {" + "\"output\": \"" + baseValue + "\"" + "}" + "}" ); JsonNode configData = mapper.readTree("{}"); JsonNode result = ConfigUtils.mergeConfigs(configData, baseConfigData); Assertions.assertTrue(result.has(TopLevelFields.AIR_OPTIONS)); JsonNode airOptions = result.get(TopLevelFields.AIR_OPTIONS); Assertions.assertTrue(airOptions.isObject()); Assertions.assertTrue(airOptions.has(AIROptions.OUTPUT)); String resultValue = airOptions.get(AIROptions.OUTPUT).asText(); Assertions.assertEquals(baseValue, resultValue); }
Example 5
Source File: GelfEncoderTest.java From logback-gelf with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void simple() throws IOException { encoder.start(); final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); final Logger logger = lc.getLogger(LOGGER_NAME); final String logMsg = encodeToStr(simpleLoggingEvent(logger, null)); final ObjectMapper om = new ObjectMapper(); final JsonNode jsonNode = om.readTree(logMsg); basicValidation(jsonNode); final LineReader msg = new LineReader(new StringReader(jsonNode.get("full_message").textValue())); assertEquals("message 1", msg.readLine()); }
Example 6
Source File: PreparationControllerTest.java From data-prep with Apache License 2.0 | 6 votes |
@Test public void shouldListErrors() throws Exception { // when final String errors = when().get("/preparations/errors").asString(); final ObjectMapper mapper = new ObjectMapper(); final JsonNode actualErrorCodes = mapper.readTree(errors); // then assertTrue(actualErrorCodes.isArray()); assertTrue(actualErrorCodes.size() > 0); for (final JsonNode currentCode : actualErrorCodes) { assertTrue(currentCode.has("code")); assertTrue(currentCode.has("http-status-code")); } }
Example 7
Source File: JsonNodeMarshallerTest.java From tasmo with Apache License 2.0 | 6 votes |
@Test(dataProviderClass = ObjectIdTestDataProvider.class, dataProvider = "createObjectId") public void testMarshaller(String className, long longId) throws Exception { JsonNodeMarshaller jsonNodeMarshaller = new JsonNodeMarshaller(); ObjectId objectId1 = new ObjectId(className, new Id(longId)); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(objectId1); JsonNode jsonNode = mapper.readTree(json); // JsonNode node = objectMapper.valueToTree(map); // JsonNode node = mapper.convertValue(object, JsonNode.class); byte[] bytes = jsonNodeMarshaller.toBytes(jsonNode); JsonNode jsonNode1 = jsonNodeMarshaller.fromBytes(bytes); ObjectId objectId2 = mapper.convertValue(jsonNode1, ObjectId.class); System.out.println("before JsonNodeMarshaller: objectId=" + objectId1.toStringForm()); System.out.println("after JsonNodeMarshaller : objectId=" + objectId2.toStringForm()); Assert.assertTrue(objectId1.equals(objectId2), " marshalled object should be equal to the original"); }
Example 8
Source File: JSLT.java From jslt with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("Usage: java com.schibsted.spt.data.jslt.cli.JSLT <jslt file> <json input file>"); System.exit(1); } Expression expr = Parser.compile(new File(args[0])); // if (expr instanceof ExpressionImpl) // ((ExpressionImpl) expr).dump(); ObjectMapper mapper = new ObjectMapper(); JsonNode input = mapper.readTree(new File(args[1])); JsonNode output = expr.apply(input); if (output == null) System.out.println("WARN: returned Java null!"); System.out.println(mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(output)); }
Example 9
Source File: GelfEncoderTest.java From logback-gelf with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void customThreadNameKey() throws IOException { encoder.setThreadNameKey("Thread"); encoder.start(); final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); final Logger logger = lc.getLogger(LOGGER_NAME); final LoggingEvent event = simpleLoggingEvent(logger, null); final String logMsg = encodeToStr(event); final ObjectMapper om = new ObjectMapper(); final JsonNode jsonNode = om.readTree(logMsg); coreValidation(jsonNode); assertNotNull(jsonNode.get("_Thread").textValue()); assertEquals(LOGGER_NAME, jsonNode.get("_logger_name").textValue()); assertNull(jsonNode.get("_exception")); }
Example 10
Source File: DhcpRelayConfigTest.java From onos with Apache License 2.0 | 5 votes |
@Test public void testInvalidConfig() throws IOException { ObjectMapper om = new ObjectMapper(); JsonNode json = om.readTree(Resources.getResource(INVALID_CONFIG_FILE_PATH)); DefaultDhcpRelayConfig config = new DefaultDhcpRelayConfig(); json = json.path("apps").path(DHCP_RELAY_APP).path(DefaultDhcpRelayConfig.KEY); config.init(APP_ID, DefaultDhcpRelayConfig.KEY, json, om, null); assertFalse(config.isValid()); }
Example 11
Source File: AristaUtils.java From onos with Apache License 2.0 | 5 votes |
public static Optional<JsonNode> retrieveCommandResult(DriverHandler handler, List<String> cmds) { RestSBController controller = checkNotNull(handler.get(RestSBController.class)); DeviceId deviceId = checkNotNull(handler.data()).deviceId(); String request = generate(cmds); log.debug("request :{}", request); String response = controller.post(deviceId, API_ENDPOINT, new ByteArrayInputStream(request.getBytes()), MediaType.APPLICATION_JSON_TYPE, String.class); log.debug("response :{}", response); try { ObjectMapper mapper = new ObjectMapper(); ObjectNode node = (ObjectNode) mapper.readTree(response); if (node.has(ERROR)) { log.error("Error {}", node.get(ERROR)); return Optional.empty(); } else { return Optional.ofNullable(node.get(RESULT)); } } catch (IOException e) { log.warn("IO exception occurred because of ", e); } return Optional.empty(); }
Example 12
Source File: JacksonUtil.java From mall with MIT License | 5 votes |
public static List<String> parseStringList(String body, String field) { ObjectMapper mapper = new ObjectMapper(); JsonNode node = null; try { node = mapper.readTree(body); JsonNode leaf = node.get(field); if (leaf != null) return mapper.convertValue(leaf, new TypeReference<List<String>>() { }); } catch (IOException e) { e.printStackTrace(); } return null; }
Example 13
Source File: RouteConfigTest.java From onos with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { InputStream jsonStream = RouteConfigTest.class .getResourceAsStream("/route-config.json"); ApplicationId subject = new TestApplicationId(KEY); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(jsonStream); ConfigApplyDelegate delegate = new MockDelegate(); config = new RouteConfig(); config.init(subject, KEY, jsonNode, mapper, delegate); }
Example 14
Source File: TestJacksonMessageWriter.java From yosegi with Apache License 2.0 | 5 votes |
@Test public void T_create_json_withNullParser() throws IOException { ObjectMapper mapper = new ObjectMapper(); JacksonMessageWriter writer = new JacksonMessageWriter(); IParser parser = null; byte[] result = writer.create( parser ); JsonNode node = mapper.readTree( result ); assertTrue( ( node instanceof NullNode ) ); }
Example 15
Source File: JsonRpcServerAnnotateMethodVarArgsTest.java From jsonrpc4j with MIT License | 5 votes |
@Test public void callMethodWithVarArgParameters() throws Exception { Map<String, Object> paramsMap = new HashMap<>(); paramsMap.put("argOne", "one"); paramsMap.put("argTwo", 2); paramsMap.put("argThree", "three"); paramsMap.put("argFour", 4); paramsMap.put("argFive", (Object) "five"); paramsMap.put("argSix", 6.0f); paramsMap.put("argSeven", 7d); Object[] callParams = new Object[paramsMap.size() * 2]; int i = 0; for (Map.Entry<String, Object> entry : paramsMap.entrySet()) { callParams[i++] = entry.getKey(); callParams[i++] = entry.getValue(); } jsonRpcServerAnnotatedMethod.handleRequest( messageWithMapParamsStream("varargObjectMethod", callParams), byteArrayOutputStream ); JsonNode res = result(); ObjectMapper mapper = new ObjectMapper(); JsonNode resultNode = mapper.readTree(res.asText()); // params order saved during call, but order not guaranteed ObjectNode expectedResult = mapper.valueToTree(paramsMap); expectedResult.set("argTwo", mapper.valueToTree(2)); expectedResult.set("argFour", mapper.valueToTree(4)); Assert.assertEquals(expectedResult.toString(), resultNode.toString()); }
Example 16
Source File: SchemaRegistryClient.java From registry with Apache License 2.0 | 5 votes |
public static CatalogResponse readCatalogResponse(String msg) { ObjectMapper objectMapper = new ObjectMapper(); try { JsonNode node = objectMapper.readTree(msg); return objectMapper.treeToValue(node, CatalogResponse.class); } catch (IOException e) { throw new RuntimeException(e); } }
Example 17
Source File: JsonSchemaValidationTest.java From microprofile-health with Apache License 2.0 | 4 votes |
private JsonNode toJsonNode(JsonObject jsonObject) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readTree(jsonObject.toString()); }
Example 18
Source File: LoginModulesTest.java From keycloak with Apache License 2.0 | 4 votes |
private void assertToken(String accessToken, boolean expectActive) throws IOException { String introspectionResponse = oauth.introspectAccessTokenWithClientCredential("customer-portal", "password", accessToken); ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(introspectionResponse); Assert.assertEquals(expectActive, jsonNode.get("active").asBoolean()); }
Example 19
Source File: JsonCompareUnitTest.java From tutorials with MIT License | 3 votes |
@Test public void givenTwoSameNestedJsonDataObjects_whenCompared_thenEqual() throws IOException { ObjectMapper mapper = new ObjectMapper(); String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"contact\":{\"email\": \"[email protected]\",\"phone\": \"9999999999\"} }}"; String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"contact\":{\"email\": \"[email protected]\",\"phone\": \"9999999999\"} }}"; JsonNode actualObj1 = mapper.readTree(s1); JsonNode actualObj2 = mapper.readTree(s2); assertEquals(actualObj1, actualObj2); }
Example 20
Source File: AbstractRestIntegrationTest.java From registry with Apache License 2.0 | 2 votes |
/** * Get response code from the response string. * * @param response * @return * @throws Exception */ public int getResponseCode(String response) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(response); return mapper.treeToValue(node.get("responseCode"), Integer.class); }