Java Examples for com.fasterxml.jackson.databind.JsonNode
The following java examples will help you to understand the usage of com.fasterxml.jackson.databind.JsonNode. These source code samples are taken from different open source projects.
Example 1
| Project: Chute-SDK-V2-Android-master File: JsonTestUtil.java View source code |
public static boolean compare(String first, String second) {
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode tree1 = mapper.readTree(first);
JsonNode tree2 = mapper.readTree(second);
return tree1.equals(tree2);
} catch (IOException e) {
}
throw new RuntimeException("Unable to compare JSON strings");
}Example 2
| Project: intellij-community-master File: continuationIndent_JsonLiteral.java View source code |
@Test
public void foo() throws Exception {
JsonNode json = test.toJson("[", " {", " \"foo\": { ", " \"bar\": 17,", " \"xyz\": 19 ", " }", " },", " {", " \"foo\": { ", " \"bar\": 17,", " \"xyz\": 19 ", " }", " },", " {", " \"foo\": { ", " \"bar\": 17,", " \"xyz\": 19 ", " }", " },", " {", " \"foo\": { ", " \"bar\": 17,", " \"xyz\": 19 ", " }", " }", "]");
}Example 3
| Project: mozu-java-master File: SecureAppDataFactory.java View source code |
public static com.fasterxml.jackson.databind.JsonNode getDBValue(ApiContext apiContext, String appKeyId, String dbEntryQuery, String responseFields, int expectedCode) throws Exception { com.fasterxml.jackson.databind.JsonNode returnObj; SecureAppDataResource resource = new SecureAppDataResource(apiContext); try { returnObj = resource.getDBValue(appKeyId, dbEntryQuery, responseFields); } catch (ApiException e) { if (e.getHttpStatusCode() != expectedCode) throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, ""); else return null; } if (expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null)) throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, ""); return returnObj; }
Example 4
| Project: Leads-QueryProcessorM-master File: ExecutionPlanConverter.java View source code |
@Override
public ExecutionPlan convert(JsonNode jsonNode) {
ObjectMapper mapper = new ObjectMapper();
try {
// OutputOperator output = mapper.readValue(jsonNode.path("output").toString(), OutputOperator.class);
Map<String, ExecutionPlanNode> graph = mapper.readValue(jsonNode.path("graph").toString(), new TypeReference<Map<String, ExecutionPlanNode>>() {
});
List<String> sources = mapper.readValue(jsonNode.path("sources").toString(), new TypeReference<List<String>>() {
});
return new ExecutionPlan(new OutputOperator("nana"), graph, sources);
} catch (IOException e) {
e.printStackTrace();
}
return new ExecutionPlan();
}Example 5
| Project: playconf-master File: RegisteredUser.java View source code |
public static RegisteredUser fromJson(JsonNode twitterJson) {
RegisteredUser u = new RegisteredUser();
u.name = twitterJson.findPath("name").asText();
u.twitterId = twitterJson.findPath("screen_name").asText();
u.description = twitterJson.findPath("description").asText();
u.pictureUrl = twitterJson.findPath("profile_image_url").asText();
return u;
}Example 6
| Project: 101simplejava-master File: TestUnparsing.java View source code |
@Test
public void testUnparse() {
File in = new File("inputs" + File.separator + "sampleCompany.json");
File out = new File("outputs" + File.separator + "outCompany.json");
JsonNode c;
c = Parsing.parseFromFile(in);
String jsonIn = "";
String jsonOut = "";
try {
Unparsing.unparse(c, out);
BufferedReader input = new BufferedReader(new FileReader(in));
BufferedReader output = new BufferedReader(new FileReader(out));
FileReader r = new FileReader(in);
while (output.ready()) jsonOut += output.readLine();
while (input.ready()) jsonIn += input.readLine();
assertEquals(0, jsonOut.compareTo(jsonIn));
output.close();
input.close();
} catch (IOException e) {
fail();
}
}Example 7
| Project: bootique-master File: PathSegmentTest.java View source code |
private static JsonNode readYaml(String yaml) {
ByteArrayInputStream in = new ByteArrayInputStream(yaml.getBytes());
try {
YAMLParser parser = new YAMLFactory().createParser(in);
return new ObjectMapper().readTree(parser);
} catch (IOException e) {
throw new RuntimeException("Error reading config file", e);
}
}Example 8
| Project: dropwizard-patch-master File: PatchUtil.java View source code |
public static <T> T copy(T object) {
if (object instanceof JsonNode) {
return (T) ((JsonNode) object).deepCopy();
}
try {
return mapper.readValue(mapper.writeValueAsString(object), mapper.getTypeFactory().constructType(object.getClass()));
} catch (IOException e) {
throw new RuntimeException("An error occurred while copying an object. See stack trace for more information.", e);
}
}Example 9
| Project: fabricator-master File: JacksonConfigurationSourceTest.java View source code |
@Test
public void test() throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);
Properties prop1 = new Properties();
prop1.setProperty("a", "_a");
prop1.setProperty("b", "_b");
prop1.setProperty("c", "_c");
JacksonComponentConfiguration source = new JacksonComponentConfiguration("key1", "type1", node);
Properties prop2 = source.getChild("properties").getValue(Properties.class);
Assert.assertEquals(prop1, prop2);
}Example 10
| Project: log-monitor-java-master File: Application.java View source code |
public WebSocket<JsonNode> streamLogs() {
return WebSocket.whenReady(( in, out) -> {
// Create new UserService and stream the current log history
final ActorRef user = Akka.system().actorOf(Props.create(UserService.class, out));
LogService.instance().tell(new LogProtocol.Watch(), user);
// on close, tell the userActor to shutdown
in.onClose(() -> {
LogService.instance().tell(new LogProtocol.Unwatch(), user);
});
});
}Example 11
| Project: marvel-rest-client-master File: CollectionURIDeserializer.java View source code |
@Override
public CollectionURI deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
CollectionURI collectionURI = new CollectionURI();
if (node.has("service")) {
String service = node.get("service").textValue();
int id = node.get("id").intValue();
collectionURI.setService(service);
collectionURI.setId(id);
} else {
collectionURI.setCollectionURI(node.textValue());
}
return collectionURI;
}Example 12
| Project: MLDS-master File: PartialCopyTest.java View source code |
@Test
public void applySomePropertiesToAnObject() throws JsonProcessingException, IOException {
ExtensionApplication extensionApplication = new ExtensionApplication();
extensionApplication.setAffiliateDetails(new AffiliateDetails());
extensionApplication.setNotesInternal("internalNotes");
String incomingJSON = "{ \"notesInternal\": \"new value\"}";
ObjectMapper objectMapper = new ObjectMapper();
ObjectReader readerForUpdating = objectMapper.readerForUpdating(extensionApplication);
JsonNode tree = objectMapper.readTree(incomingJSON);
readerForUpdating.readValue(tree);
Assert.assertEquals("new value", extensionApplication.getNotesInternal());
}Example 13
| Project: neo4j-play2java-master File: StudentControllerTest.java View source code |
@Test
public void testGetUser() {
Student student = new Student();
student.setName("My Test");
JsonNode jsonNode = Json.toJson(student);
Result result = route(fakeRequest(POST, "/student").bodyJson(jsonNode));
assertNotNull(result);
assertEquals(200, result.status());
System.out.println(result.toString());
}Example 14
| Project: open-data-service-master File: PegelOnlineHealthCheck.java View source code |
@Override
protected Result check() throws Exception {
JsonNode json = mapper.readTree(new URL("http://pegelonline.wsv.de/webservices/rest-api/v2/stations.json").openStream());
if (!json.isArray())
return Result.unhealthy("pegelonline did not return JSON array");
if (json.size() == 0)
return Result.unhealthy("pegelonline returned empty JSON");
return Result.healthy();
}Example 15
| Project: prospecter-master File: GenericFieldHandler.java View source code |
public List<ClauseNode> getConditions() {
List<ClauseNode> conditions = new ArrayList<ClauseNode>();
String comparator = root.get("condition").asText();
MatchCondition matchCondition = getMatchCondition(comparator);
boolean not = false;
if (root.get("not") != null) {
not = root.get("not").asBoolean(false);
}
JsonNode valNode = getValue();
if (valNode.getNodeType() == JsonNodeType.ARRAY) {
List<Token> tokens = new ArrayList<Token>();
for (JsonNode node : valNode) {
tokens.add(getToken(node, matchCondition));
}
conditions.add(new Condition(fieldName, new Token<List<Token>>(tokens, MatchCondition.IN), not));
} else {
conditions.add(new Condition(fieldName, getToken(valNode, matchCondition), not));
}
return conditions;
}Example 16
| Project: spring-social-tumblr-master File: TumblrResponseMixin.java View source code |
@Override
public TumblrResponse deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode root = jp.readValueAsTree();
TumblrResponse response = new TumblrResponse();
JsonNode meta = root.get("meta");
response.setStatus(meta.get("status").intValue());
response.setMessage(meta.get("msg").textValue());
response.setResponseJson(root.get("response").toString());
return response;
}Example 17
| Project: swagger-core-master File: SecurityDefinitionDeserializer.java View source code |
@Override
public SecuritySchemeDefinition deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
SecuritySchemeDefinition result = null;
JsonNode node = jp.getCodec().readTree(jp);
JsonNode inNode = node.get("type");
if (inNode != null) {
String type = inNode.asText();
if ("basic".equals(type)) {
result = Json.mapper().convertValue(node, BasicAuthDefinition.class);
} else if ("apiKey".equals(type)) {
result = Json.mapper().convertValue(node, ApiKeyAuthDefinition.class);
} else if ("oauth2".equals(type)) {
result = Json.mapper().convertValue(node, OAuth2Definition.class);
}
}
return result;
}Example 18
| Project: swagger-parser-master File: SimpleSwaggerReader.java View source code |
@Override public JsonNode read(final String url, final Authentication authentication, MessageBuilder messageBuilder) { HttpClient httpClient = new io.swagger.io.HttpClient(url); JsonNode jsonNode = null; authentication.apply(httpClient); try { InputStream swaggerJson = httpClient.execute(); jsonNode = objectMapper.readTree(swaggerJson); } catch (URISyntaxExceptionIOException | e) { messageBuilder.append(new Message("", e.getMessage(), Severity.ERROR)); } httpClient.close(); return jsonNode; }
Example 19
| Project: tzatziki-master File: LoadJson.java View source code |
public JsonNode loadFromResource(String resourceName) throws IOException { InputStream in = getClass().getResourceAsStream(resourceName); try { Reader reader = new InputStreamReader(in, charsetName); ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(reader, JsonNode.class); } finally { IOUtils.closeQuietly(in); } }
Example 20
| Project: verjson-master File: Example2Transformation.java View source code |
@Override protected void transform(JsonNode node) { ObjectNode obj = obj(node); // remove first remove(obj, "first"); // rename second rename(obj, "second", "segundo"); // keep third and fourth // convert fifth ArrayNode fifth = getArrayAndRemove(obj, "fifth"); if (fifth != null) { StringBuilder builder = new StringBuilder(); for (JsonNode elem : fifth) { builder.append(elem.asText()); } obj.put("fifth", builder.toString()); } // convert sixth ObjectNode sixth = getObjAndRemove(obj, "sixth"); rename(sixth, "one", "uno"); remove(sixth, "two"); // rename SubB rename(obj(obj.get("subB")), "bbb", "ccc"); obj.set("sixth", createArray(sixth)); }
Example 21
| Project: WAMPlay-master File: SubscribeHandler.java View source code |
@Override
public void process(WAMPlayClient senderClient, JsonNode message) {
String topic = message.get(1).asText();
PubSubCallback cb = PubSub.getPubSubCallback(topic);
if (cb == null) {
log.error("Topic not found: " + topic);
return;
}
boolean sucessful = cb.runSubCallback(senderClient.getSessionID());
if (!sucessful) {
log.debug("Callback for " + topic + " canceled.");
return;
}
if (WAMPlayServer.isTopic(topic)) {
senderClient.subscribe(topic);
return;
}
log.error("Client tried to subscribe to nonexistant topic: " + topic);
}Example 22
| Project: ache-master File: TitleRegexTargetClassifier.java View source code |
public TargetClassifier build(Path basePath, ObjectMapper yaml, JsonNode parameters) throws JsonProcessingException {
TitleRegexClassifierConfig params = yaml.treeToValue(parameters, TitleRegexClassifierConfig.class);
if (params.regular_expression != null && !params.regular_expression.trim().isEmpty()) {
return new TitleRegexTargetClassifier(params.regular_expression.trim());
} else {
return null;
}
}Example 23
| Project: Activiti-master File: ExecutionActiveActivitiesCollectionResourceTest.java View source code |
@Deployment
public void testGetActivities() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("processOne");
CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_EXECUTION_ACTIVITIES_COLLECTION, processInstance.getId())), HttpStatus.SC_OK);
// Check resulting instance
JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
closeResponse(response);
assertNotNull(responseNode);
assertTrue(responseNode.isArray());
assertEquals(2, responseNode.size());
Set<String> states = new HashSet<String>();
states.add(responseNode.get(0).textValue());
states.add(responseNode.get(1).textValue());
assertTrue(states.contains("waitState"));
assertTrue(states.contains("anotherWaitState"));
}Example 24
| Project: Acuitra-master File: NLPMapToDBpediaOntOrPropQueryStage.java View source code |
protected List<String> mapPropertyToRDFPredicate(String property) {
List<String> results = new ArrayList<>();
StringBuilder builder = new StringBuilder();
builder.append("PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> ");
builder.append("SELECT ?subject WHERE '{' ");
builder.append("?subject rdfs:label \"{0}\" @en");
builder.append(" '}' ");
String output = SparqlUtils.runQuery(this.context.getJerseyClient(), sparqlEndpointURL, builder.toString(), property);
//
// Result looks like this
//
// {
// head: {
// vars: [
// "subject"
// ]
// },
// results: {
// bindings: [
// {
// subject: {
// type: "uri",
// value: "http://dbpedia.org/resource/U.S."
// }
// }
// ]
// }
//
// }
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode rootNode = mapper.readTree(output);
int answerCount = rootNode.path("results").path("bindings").size();
for (int i = 0; i < answerCount; i++) {
String answerValue = rootNode.path("results").path("bindings").path(i).path("subject").path("value").asText();
if (!answerValue.startsWith("<")) {
answerValue = "<" + answerValue;
}
if (!answerValue.endsWith(">")) {
answerValue = answerValue + ">";
}
results.add(answerValue);
}
return results;
} catch (IOException e) {
throw new RuntimeException(e);
}
}Example 25
| Project: amos-ss15-proj2-master File: PlacesManager.java View source code |
public List<Place> getNearbyPlaces(Map<String, String> queryMap, int maxResults) {
ObjectNode jsonResult = placesApi.getNearybyPlaces(queryMap);
JsonNode jsonPlaces = jsonResult.path("results");
int count = 0;
List<Place> places = new ArrayList<>();
for (JsonNode jsonPlace : jsonPlaces) {
if (count >= maxResults)
break;
++count;
JsonNode jsonLocation = jsonPlace.path("geometry").path("location");
Place place = new Place(jsonPlace.path("name").asText(), new RouteLocation(jsonLocation.path("lat").asDouble(), jsonLocation.path("lng").asDouble()));
places.add(place);
}
return places;
}Example 26
| Project: apiman-plugins-master File: XmlToJsonTransformerTest.java View source code |
private void test(String xmlFileName, String jsonFileName) throws Exception {
String xml = readFile(xmlFileName);
String expectedJson = readFile(jsonFileName);
String actualJson = transformer.transform(xml);
ObjectMapper mapper = new ObjectMapper();
JsonNode expectedJsonNode = mapper.readTree(expectedJson);
JsonNode actualJsonNode = mapper.readTree(actualJson);
assertTrue(expectedJsonNode.equals(actualJsonNode));
}Example 27
| Project: arangodb-objectmapper-master File: ResponseCallback.java View source code |
/**
* Error handler (throws ArangoDb4JException)
*
* @param hr
* Request response
*
* @return T
*
* @throws ArangoDb4JException
*/
public T error(ArangoDbHttpResponse hr) throws ArangoDb4JException {
ObjectMapper om = new ObjectMapper();
JsonNode root;
try {
root = om.readTree(hr.getContentAsStream());
} catch (Exception e) {
throw new ArangoDb4JException(e.getMessage(), hr.getCode(), 0);
}
String errorMessage = root.has("errorMessage") ? root.get("errorMessage").asText() : null;
Integer errorNum = root.has("errorNum") ? root.get("errorNum").asInt() : null;
throw new ArangoDb4JException(errorMessage, hr.getCode(), errorNum);
}Example 28
| Project: ark-tweet-nlp-master File: JsonTweetReader.java View source code |
/**
* Get the text from a raw Tweet JSON string.
*
* @param tweetJson
* @return null if there is no text field, or invalid JSON.
*/
public String getText(String tweetJson) {
JsonNode rootNode;
try {
rootNode = mapper.readValue(tweetJson, JsonNode.class);
} catch (JsonParseException e) {
return null;
} catch (IOException e) {
return null;
}
if (!rootNode.isObject())
return null;
JsonNode textValue = rootNode.get("text");
if (textValue == null)
return null;
return textValue.asText();
}Example 29
| Project: baasbox-master File: ScriptTestHelpers.java View source code |
public static JsonNode loadScript(String name, String source) {
try (InputStream in = Play.application().resourceAsStream(source)) {
String code = IOUtils.toString(in, Charset.defaultCharset());
ObjectNode script = Json.mapper().createObjectNode();
script.put(ScriptsDao.NAME, name);
script.put(ScriptsDao.CODE, code);
script.put(ScriptsDao.ACTIVE, true);
script.put(ScriptsDao.LANG, ScriptLanguage.JS.name);
script.put(ScriptsDao.LIB, false);
return script;
} catch (IOException e) {
Assert.fail(ExceptionUtils.getFullStackTrace(e));
throw new RuntimeException(e);
}
}Example 30
| Project: bce-sdk-java-master File: WriteRequestUnmarshaller.java View source code |
@Override public WriteRequest unmarshall(JsonNode jsonObj) throws Exception { WriteRequest req = null; JsonNode putNode = jsonObj.get(MolaDbConstants.JSON_PUT_REQUEST); JsonNode delNode = jsonObj.get(MolaDbConstants.JSON_DELETE_REQUEST); if ((null == putNode && null == delNode) || (null != putNode && null != delNode)) { throw new BceClientException("Invalid responseContent json:" + jsonObj.toString()); } if (null != putNode) { PutRequestUnmarshaller unmarshaller = new PutRequestUnmarshaller(); PutRequest putRequest = unmarshaller.unmarshall(putNode); req = putRequest; } else { DeleteRequestUnmarshaller unmarshaller = new DeleteRequestUnmarshaller(); DeleteRequest delRequest = unmarshaller.unmarshall(delNode); req = delRequest; } return req; }
Example 31
| Project: beakerx-master File: TabbedOutputContainerLayoutManagerDeserializerTest.java View source code |
@Test
public void deserialize_resultObjectHasBorderDisplayed() throws Exception {
//given
boolean borderDisplayed = true;
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree("{\"type\":\"TabbedOutputContainerLayoutManager\",\"borderDisplayed\":\"" + borderDisplayed + "\"}");
TabbedOutputContainerLayoutManagerDeserializer deserializer = new TabbedOutputContainerLayoutManagerDeserializer(new BasicObjectSerializer());
//when
TabbedOutputContainerLayoutManager layoutManager = (TabbedOutputContainerLayoutManager) deserializer.deserialize(actualObj, mapper);
//then
Assertions.assertThat(layoutManager).isNotNull();
Assertions.assertThat(layoutManager.isBorderDisplayed()).isEqualTo(borderDisplayed);
}Example 32
| Project: cicada-master File: IndexConfigLoader.java View source code |
public String load(final String type) {
final String path = ROOTDIR + type + ".settings";
InputStream in = null;
JsonNode node = null;
try {
in = IndexConfigLoader.class.getResourceAsStream(path);
node = new ObjectMapper().readTree(in);
return node.toString();
} catch (Exception ex) {
log.error("failed load config from path: {}, error: {}", path, ex);
throw new RuntimeException("failed load index config from path: " + path);
} finally {
try {
in.close();
} catch (//
Exception //
ex) {
}
}
}Example 33
| Project: cloudbreak-master File: BlueprintCreationTest.java View source code |
@Test
@Parameters({ "blueprintName", "blueprintFile" })
public void testBlueprintCreation(@Optional("it-hdp-multi-blueprint") String blueprintName, @Optional("classpath:/blueprint/hdp-multinode-default.bp") String blueprintFile) throws Exception {
// GIVEN
String blueprintContent = ResourceUtil.readStringFromResource(applicationContext, blueprintFile);
// WHEN
BlueprintRequest blueprintRequest = new BlueprintRequest();
blueprintRequest.setName(blueprintName);
blueprintRequest.setDescription("Blueprint for integration testing");
blueprintRequest.setAmbariBlueprint(mapper.readValue(blueprintContent, JsonNode.class));
String id = getCloudbreakClient().blueprintEndpoint().postPrivate(blueprintRequest).getId().toString();
// THEN
Assert.assertNotNull(id);
getItContext().putContextParam(CloudbreakITContextConstants.BLUEPRINT_ID, id, true);
}Example 34
| Project: cyREST-master File: GroupTest.java View source code |
@Test
public void testGetGroups() throws Exception {
final Long suid = network.getSUID();
final Response result = target("/v1/networks/" + suid + "/groups").request().get();
assertNotNull(result);
assertEquals(200, result.getStatus());
System.out.println("res: " + result.toString());
final String body = result.readEntity(String.class);
System.out.println(body);
final JsonNode root = mapper.readTree(body);
assertTrue(root.isArray());
assertEquals(0, root.size());
}Example 35
| Project: eManga-master File: PageDeserializer.java View source code |
@Override
public Page deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
String _id = node.get("_id").get("$oid").asText();
Integer number = null;
JsonNode numberNode = node.get("number");
if (numberNode != null && !(numberNode instanceof NullNode)) {
number = numberNode.asInt();
}
String url = null;
JsonNode urlNode = node.get("url");
if (urlNode != null && !(urlNode instanceof NullNode)) {
url = urlNode.asText();
}
return new Page(_id, number, url, null);
}Example 36
| Project: EnrichmentMapApp-master File: Rectangle2DJsonDeserializer.java View source code |
@Override
public Rectangle2D deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
final ObjectCodec oc = jp.getCodec();
final JsonNode node = oc.readTree(jp);
final JsonNode xNode = node.get("x");
final JsonNode yNode = node.get("y");
final JsonNode wNode = node.get("width");
final JsonNode hNode = node.get("height");
final double x = xNode != null && xNode.isNumber() ? xNode.asDouble() : 0;
final double y = yNode != null && yNode.isNumber() ? yNode.asDouble() : 0;
final double w = wNode != null && wNode.isNumber() ? wNode.asDouble() : 0;
final double h = hNode != null && hNode.isNumber() ? hNode.asDouble() : 0;
return new Rectangle2D.Double(x, y, w, h);
}Example 37
| Project: evrythng-java-sdk-master File: Deserializer.java View source code |
protected final <X> X getFieldValue(final JsonNode node) {
if (node == null) {
return null;
}
Object value = null;
if (node.isBoolean()) {
value = node.asBoolean();
}
if (node.isNumber()) {
value = node.asDouble();
}
if (node.isTextual()) {
value = node.asText();
}
if (node.isArray()) {
value = new ArrayList<>();
}
if (node.isObject()) {
value = new HashMap<>();
}
return (X) value;
}Example 38
| Project: hamcrest-jackson-master File: IsJson.java View source code |
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
try {
JsonNode jsonNode = new ObjectMapper().readTree(item);
if (matcher.matches(jsonNode)) {
return true;
} else {
matcher.describeMismatch(jsonNode, mismatchDescription);
return false;
}
} catch (IOException e) {
mismatchDescription.appendText("Invalid JSON");
return false;
}
}Example 39
| Project: handlebars.java-master File: Issue368.java View source code |
@Test
public void jsonItShouldHaveIndexVar() throws IOException {
String value = "{ \"names\": [ { \"id\": \"a\" }, { \"id\": \"b\" }, { \"id\": \"c\" }, { \"id\": \"d\" } ] }";
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(value);
shouldCompileTo("{{#each names}}index={{@index}}, id={{id}}, {{/each}}", jsonNode, "index=0, id=a, index=1, id=b, index=2, id=c, index=3, id=d, ");
}Example 40
| Project: htwplus-master File: WebSocketActor.java View source code |
@Override
public void onReceive(Object message) throws Exception {
try {
// write response to WebSocket channel by invoking WebSocket method with given
// input WebSocket data parameters and the ActorRef of this
this.out.write(webSocketService.invokeWsMethod((JsonNode) message, this.self(), this.account));
} catch (Throwable ex) {
unhandled(ex.getMessage());
this.context().stop(this.self());
}
}Example 41
| Project: jackson-datatype-guava-master File: HostAndPortDeserializer.java View source code |
@Override
public HostAndPort deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
// since we have legacy JSON Object format to support too:
if (jp.getCurrentToken() == JsonToken.START_OBJECT) {
// old style
JsonNode root = jp.readValueAsTree();
String host = root.path("hostText").asText();
JsonNode n = root.get("port");
if (n == null) {
return HostAndPort.fromString(host);
}
return HostAndPort.fromParts(host, n.asInt());
}
return super.deserialize(jp, ctxt);
}Example 42
| Project: java-jwt-master File: HeaderDeserializer.java View source code |
@Override
public BasicHeader deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
Map<String, JsonNode> tree = p.getCodec().readValue(p, new TypeReference<Map<String, JsonNode>>() {
});
if (tree == null) {
throw new JWTDecodeException("Parsing the Header's JSON resulted on a Null map");
}
String algorithm = getString(tree, PublicClaims.ALGORITHM);
String type = getString(tree, PublicClaims.TYPE);
String contentType = getString(tree, PublicClaims.CONTENT_TYPE);
String keyId = getString(tree, PublicClaims.KEY_ID);
return new BasicHeader(algorithm, type, contentType, keyId, tree);
}Example 43
| Project: jml-master File: PackedUnsignedLong.java View source code |
@Override
public PackedUnsignedLong deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
final int lowerbits;
final int upperbits;
if (node.isArray()) {
lowerbits = node.get(0).asInt();
upperbits = node.get(1).asInt();
} else {
lowerbits = node.asInt();
upperbits = 0;
}
return new PackedUnsignedLong(lowerbits, upperbits);
}Example 44
| Project: JSON-RPC-master File: AnnotationsErrorResolver.java View source code |
/**
* {@inheritDoc}
*/
@Override
public JsonError resolveError(Throwable thrownException, Method method, List<JsonNode> arguments) {
JsonRpcError resolver = getResolverForException(thrownException, method);
if (notFoundResolver(resolver))
return null;
String message = hasErrorMessage(resolver) ? resolver.message() : thrownException.getMessage();
return new JsonError(resolver.code(), message, new ErrorData(resolver.exception().getName(), message));
}Example 45
| Project: json-schema-validation-master File: ReflectionKeywordValidatorFactory.java View source code |
@Override
public KeywordValidator getKeywordValidator(JsonNode node) throws ProcessingException {
try {
return constructor.newInstance(node);
} catch (InstantiationException e) {
throw new ProcessingException(ERRMSG, e);
} catch (IllegalAccessException e) {
throw new ProcessingException(ERRMSG, e);
} catch (InvocationTargetException e) {
throw new ProcessingException(ERRMSG, e);
}
}Example 46
| Project: json-schema-validator-demo-master File: SyntaxProcessing.java View source code |
@Override protected JsonNode buildResult(final String input) throws IOException, ProcessingException { final ObjectNode ret = FACTORY.objectNode(); final boolean invalidSchema = fillWithData(ret, INPUT, INVALID_INPUT, input); final JsonNode schemaNode = ret.remove(INPUT); if (invalidSchema) return ret; final ProcessingReport report = VALIDATOR.validateSchema(schemaNode); final boolean success = report.isSuccess(); ret.put(VALID, success); ret.put(RESULTS, JacksonUtils.prettyPrint(buildReport(report))); return ret; }
Example 47
| Project: json-schema-validator-master File: ReflectionKeywordValidatorFactory.java View source code |
@Override
public KeywordValidator getKeywordValidator(JsonNode node) throws ProcessingException {
try {
return constructor.newInstance(node);
} catch (InstantiationException e) {
throw new ProcessingException(ERRMSG, e);
} catch (IllegalAccessException e) {
throw new ProcessingException(ERRMSG, e);
} catch (InvocationTargetException e) {
throw new ProcessingException(ERRMSG, e);
}
}Example 48
| Project: jsonrpc4j-master File: AnnotationsErrorResolver.java View source code |
/**
* {@inheritDoc}
*/
@Override
public JsonError resolveError(Throwable thrownException, Method method, List<JsonNode> arguments) {
JsonRpcError resolver = getResolverForException(thrownException, method);
if (notFoundResolver(resolver))
return null;
String message = hasErrorMessage(resolver) ? resolver.message() : thrownException.getMessage();
return new JsonError(resolver.code(), message, new ErrorData(resolver.exception().getName(), message));
}Example 49
| Project: katharsis-core-master File: RequestBodyDeserializer.java View source code |
@Override
public RequestBody deserialize(JsonParser jp, DeserializationContext deserializationContext) throws IOException {
JsonNode node = jp.readValueAsTree();
if (node == null) {
return null;
}
RequestBody requestBody = new RequestBody();
JsonNode data = node.get("data");
Object value;
if (data != null) {
if (data.isArray()) {
Iterator<JsonNode> nodeIterator = data.iterator();
List<DataBody> dataBodies = new LinkedList<>();
while (nodeIterator.hasNext()) {
DataBody newLinkage = jp.getCodec().treeToValue(nodeIterator.next(), DataBody.class);
dataBodies.add(newLinkage);
}
value = dataBodies;
} else if (data.isObject()) {
value = jp.getCodec().treeToValue(data, DataBody.class);
} else if (data.isNull()) {
value = null;
} else {
throw new RuntimeException("data field has wrong type: " + data.toString());
}
requestBody.setData(value);
}
return requestBody;
}Example 50
| Project: Koral-master File: CollectionQueryDuplicateTest.java View source code |
@Test
public void testCollectionQueryDuplicateThrowsAssertionException() throws IOException {
QuerySerializer serializer = new QuerySerializer();
serializer.setQuery("[base=Haus]", "poliqarp");
serializer.setCollection("textClass=politik & corpusID=WPD");
ObjectMapper m = new ObjectMapper();
JsonNode first = m.readTree(serializer.toJSON());
assertNotNull(first);
assertEquals(first.at("/collection"), m.readTree(serializer.toJSON()).at("/collection"));
assertEquals(first.at("/collection"), m.readTree(serializer.toJSON()).at("/collection"));
assertEquals(first.at("/collection"), m.readTree(serializer.toJSON()).at("/collection"));
}Example 51
| Project: lightblue-client-master File: LightblueTestHarnessConfigFactory.java View source code |
/**
* Combines multiple sources of metadata.
*/
public static LightblueTestHarnessConfig allOf(LightblueTestHarnessConfig... testMethods) {
return new LightblueTestHarnessConfig() {
@Override
public JsonNode[] getMetadataJsonNodes() throws Exception {
return Arrays.stream(testMethods).flatMap( m -> {
try {
return Arrays.stream(m.getMetadataJsonNodes());
} catch (Exception e) {
throw new RuntimeException(e);
}
}).distinct().toArray(JsonNode[]::new);
}
};
}Example 52
| Project: lightblue-migrator-master File: InterruptibleStuckMigrator.java View source code |
public List<JsonNode> getSourceDocuments() {
LOGGER.debug("getSourceDocuments start");
Breakpoint.checkpoint("Migrator:getSourceDocuments");
while (true) {
LOGGER.debug("getSourceDocuments waiting");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
numInterrupted++;
Breakpoint.checkpoint("Migrator:interrupted");
LOGGER.debug("getSourceDocuments interrupt");
throw new RuntimeException(e);
}
}
}Example 53
| Project: lobid-master File: SearchResourceSortOrder.java View source code |
/*@formatter:on@*/
private static void search(final String request, final List<String> years) {
running(TEST_SERVER, new Runnable() {
@Override
public void run() {
String response = call(request);
assertThat(response).isNotNull();
JsonNode json = Json.parse(response);
List<String> issued = json.findValuesAsText("issued");
assertThat(issued).isEqualTo(years);
}
});
}Example 54
| Project: maxwell-master File: ColumnDefDeserializer.java View source code |
@Override
public ColumnDef deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
String type = node.get("type").asText();
String name = node.get("name").asText();
String charset = node.path("charset").asText();
boolean signed = node.path("signed").asBoolean(false);
String[] enumValues = null;
JsonNode enumValueNode = node.get("enum-values");
if (enumValueNode != null) {
ArrayList<String> values = new ArrayList<>();
for (JsonNode n : enumValueNode) values.add(n.asText());
enumValues = (String[]) values.toArray(new String[0]);
}
Long columnLength = null;
JsonNode columnLengthNode = node.get("column-length");
if (columnLengthNode != null) {
columnLength = columnLengthNode.asLong();
}
return ColumnDef.build(name, charset, type, 0, signed, enumValues, columnLength);
}Example 55
| Project: myfda-master File: DrugControllerIT.java View source code |
@Test
public void testAutoComplete() throws Exception {
MvcResult result = mockMvc.perform(get("/autocomplete?name=Adv")).andExpect(status().isOk()).andReturn();
JsonNode node = objectMapper.readTree(result.getResponse().getContentAsString());
assertNotNull(node);
assertTrue(node.isArray());
assertTrue(node.size() > 8);
assertTrue(node.get(0).asText().trim().equalsIgnoreCase("ADVAIR"));
assertTrue(node.get(7).asText().trim().equalsIgnoreCase("ADVICOR"));
assertTrue(node.get(8).asText().trim().equalsIgnoreCase("ADVIL"));
}Example 56
| Project: NemakiWare-master File: SearchEngine.java View source code |
public static Result init(String repositoryId) {
JsonNode result = Util.getJsonResponse(session(), getEndpoint(repositoryId) + "init");
String status = result.get(Token.REST_STATUS).textValue();
if (Token.REST_SUCCESS.equals(status)) {
return ok();
} else {
return badRequest(result.get(Token.REST_ERROR));
}
}Example 57
| Project: nextprot-api-master File: PepXIntegrationTest.java View source code |
//That's how it is used by uniqueness checker tool
@Test
public void shouldReturnSomePeptidesForUniquenessCheckerTool() throws Exception {
String content = this.mockMvc.perform(get("/entries/search/peptide").param("peptide", "CLLCALK").param("modeIL", "true")).andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)).andReturn().getResponse().getContentAsString();
ObjectMapper om = new ObjectMapper();
JsonNode actualObj = om.readTree(content);
// Ensures that the viewer of phenotypes are not broken
String peptideName = actualObj.get(0).get("annotationsByCategory").get("pepx-virtual-annotation").get(0).get("cvTermName").toString();
Assert.assertTrue(peptideName.contains("\"CLLCALK\""));
}Example 58
| Project: ovsdb-master File: OvsdbSchemaTest.java View source code |
/**
* Test OVSDB schema construction from JSON text in
* test_schema.json. Following tables are used: "Port", "Manager",
* "Bridge", "Interface", "SSL", "Open_vSwitch", "Queue",
* "NetFlow", "Mirror", "QoS", "Controller", "Flow_Table", "sFlow"
* tables.
*/
@Test
public void testSchema() throws IOException {
InputStream resourceAsStream = OvsdbSchemaTest.class.getResourceAsStream("test_schema.json");
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(resourceAsStream);
DatabaseSchema schema = DatabaseSchema.fromJson("some", jsonNode.get("result"));
assertNotNull(schema);
assertEquals(Version.fromString("6.12.0"), schema.getVersion());
}Example 59
| Project: pair-java-master File: ProductSearchCardSerializationTest.java View source code |
@Test
public void serializeProductSearchCardTest() throws IOException {
JsonNode inputNode = mapper.readTree(inputString);
ProductSearchCard card = mapper.readValue(inputString, ProductSearchCard.class);
JsonNode outputNode = mapper.readTree(card.writeAsJsonString());
TestCase.assertEquals("Expected inputNode and outputNode sizes to match", inputNode.size(), outputNode.size());
Iterator<String> inputItr = inputNode.fieldNames();
Iterator<String> outputItr = outputNode.fieldNames();
while (inputItr.hasNext()) {
String inFieldName = inputItr.next();
String outFieldName = outputItr.next();
Assert.assertEquals("Expected " + inFieldName + " to match", inputNode.get(inFieldName), outputNode.get(outFieldName));
}
}Example 60
| Project: play-jaas-master File: User.java View source code |
public static void main(String[] args) {
User u = new User();
u.name = "johndoe";
u.fullName = "John Doe";
String json = u.toJson();
System.out.println("JSON: " + json);
u = User.fromJson(json);
System.out.println("User: " + u.toJson());
JsonNode n = Json.toJson(u);
json = Json.stringify(n);
System.out.println("json: " + json);
u = User.fromJson(json);
System.out.println("User: " + u.toJson());
}Example 61
| Project: publicplay-master File: BulkUser.java View source code |
public List<User> toModel() {
if (log.isDebugEnabled())
log.debug("toModel() <-");
JsonNode jsnode = parse(bulkData);
if (log.isDebugEnabled())
log.debug("jsnode : " + jsnode);
List<User> list = new ArrayList<User>();
@SuppressWarnings("unchecked") List<Object> objects = fromJson(jsnode, List.class);
for (Object o : objects) {
JsonNode json = toJson(o);
User user = fromJson(json, User.class);
user.setStatus(Status.NEW);
list.add(user);
}
if (log.isDebugEnabled())
log.debug("list : " + list);
return list;
}Example 62
| Project: raml-mock-server-master File: JsonContentValidator.java View source code |
public ValidationErrors validate(String schema, String requestBody) {
ValidationErrors errors = new ValidationErrors();
try {
JsonNode schemaNode = JsonLoader.fromString(schema);
JsonNode dataNode = JsonLoader.fromString(requestBody);
ProcessingReport report = JsonSchemaFactory.byDefault().getJsonSchema(schemaNode).validate(dataNode);
if (!report.isSuccess())
report.iterator().forEachRemaining( m -> errors.addMessage("[ %s ] [ body ] %s", bodyType, m.getMessage()));
} catch (Exception e) {
errors.addMessage("[ %s ] [ body ] Unexpected error of [ %s ] while validating JSON content", bodyType, e.getMessage());
}
return errors;
}Example 63
| Project: shimmer-master File: DataPointMapperUnitTests.java View source code |
/**
* @param classPathResourceName the name of the class path resource to load
* @return the contents of the resource as a {@link JsonNode}
* @throws RuntimeException if the resource can't be loaded
*/
protected JsonNode asJsonNode(String classPathResourceName) {
ClassPathResource resource = new ClassPathResource(classPathResourceName);
try {
InputStream resourceInputStream = resource.getInputStream();
return objectMapper.readTree(resourceInputStream);
} catch (IOException e) {
throw new RuntimeException(format("The class path resource '%s' can't be loaded as a JSON node.", classPathResourceName), e);
}
}Example 64
| Project: spring-security-oauth-master File: FacebookController.java View source code |
@RequestMapping("/facebook/info")
public String photos(Model model) throws Exception {
ObjectNode result = facebookRestTemplate.getForObject("https://graph.facebook.com/me/friends", ObjectNode.class);
ArrayNode data = (ArrayNode) result.get("data");
ArrayList<String> friends = new ArrayList<String>();
for (JsonNode dataNode : data) {
friends.add(dataNode.get("name").asText());
}
model.addAttribute("friends", friends);
return "facebook";
}Example 65
| Project: threatconnect-java-master File: GenericIndicatorResponseDataDeserializer.java View source code |
//THIS IS NOT NEEDED for now, will refactor to make it to work later if we have the case
@Override
public GenericIndicatorResponseData deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
GenericIndicatorResponseData result = new GenericIndicatorResponseData();
ObjectCodec oc = p.getCodec();
ObjectNode rootNode = oc.readTree(p);
Iterator<String> keys = rootNode.fieldNames();
if (keys.hasNext()) {
String key = (String) keys.next();
//result.setType(key);
JsonNode value = rootNode.get(key);
CustomIndicator obj = oc.treeToValue(value, CustomIndicator.class);
//obj.setType(key);
obj.setIndicatorType(key);
//result.setCustomIndicator(obj);
}
return result;
}Example 66
| Project: Toga-master File: SchemaValidator.java View source code |
public ProcessingReport validate(String input) {
if (schema == null) {
throw new IllegalStateException("Tried to validate without schema.");
}
try {
final JsonNode dataNode = fromString(input);
return schema.validate(dataNode);
} catch (IOExceptionProcessingException | e) {
throw new RuntimeException("Exception while validating.", e);
}
}Example 67
| Project: unikitty-master File: DrugControllerIT.java View source code |
@Test
public void testAutoComplete() throws Exception {
MvcResult result = mockMvc.perform(get("/autocomplete?name=Adv")).andExpect(status().isOk()).andReturn();
JsonNode node = objectMapper.readTree(result.getResponse().getContentAsString());
assertNotNull(node);
assertTrue(node.isArray());
assertTrue(node.size() > 8);
assertTrue(node.get(0).asText().trim().equalsIgnoreCase("ADVAIR"));
assertTrue(node.get(7).asText().trim().equalsIgnoreCase("ADVICOR"));
assertTrue(node.get(8).asText().trim().equalsIgnoreCase("ADVIL"));
}Example 68
| Project: useful-java-links-master File: JsonSchemaValidatorHelloWorld.java View source code |
public static void main(final String... args) throws IOException, ProcessingException {
final JsonNode fstabSchema = Utils.loadResource("/fstab.json");
final JsonNode good = Utils.loadResource("/fstab-good.json");
final JsonNode bad = Utils.loadResource("/fstab-bad.json");
final JsonNode bad2 = Utils.loadResource("/fstab-bad2.json");
final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
final JsonSchema schema = factory.getJsonSchema(fstabSchema);
ProcessingReport report;
report = schema.validate(good);
System.out.println(report);
report = schema.validate(bad);
System.out.println(report);
report = schema.validate(bad2);
System.out.println(report);
}Example 69
| Project: XChange-master File: QuadrigaCxErrorDeserializer.java View source code |
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
if (node.isTextual()) {
return node.textValue();
} else if (node.isObject()) {
JsonNode allNode = node.get("__all__");
if (allNode != null && allNode.isArray()) {
StringBuffer buf = new StringBuffer();
for (JsonNode msgNode : allNode) {
buf.append(msgNode.textValue());
buf.append(",");
}
return buf.length() > 0 ? buf.substring(0, buf.length() - 1) : buf.toString();
}
return node.toString();
}
return null;
}Example 70
| Project: keycloak-master File: MicrosoftIdentityProvider.java View source code |
@Override
protected BrokeredIdentityContext doGetFederatedIdentity(String accessToken) {
try {
String URL = PROFILE_URL + "?access_token=" + URLEncoder.encode(accessToken, "UTF-8");
if (log.isDebugEnabled()) {
log.debug("Microsoft Live user profile request to: " + URL);
}
JsonNode profile = JsonSimpleHttp.asJson(SimpleHttp.doGet(URL, session));
String id = getJsonProperty(profile, "id");
String email = null;
if (profile.has("emails")) {
email = getJsonProperty(profile.get("emails"), "preferred");
}
BrokeredIdentityContext user = new BrokeredIdentityContext(id);
user.setUsername(email != null ? email : id);
user.setFirstName(getJsonProperty(profile, "first_name"));
user.setLastName(getJsonProperty(profile, "last_name"));
if (email != null)
user.setEmail(email);
user.setIdpConfig(getConfig());
user.setIdp(this);
AbstractJsonUserAttributeMapper.storeUserProfileForMapper(user, profile, getConfig().getAlias());
return user;
} catch (Exception e) {
throw new IdentityBrokerException("Could not obtain user profile from Microsoft Live ID.", e);
}
}Example 71
| Project: action-core-master File: RowFactory.java View source code |
/**
* Return the right row associated with some data.
* <p/>
* The decoding from Hadoop was done in the RowSerializers. This utility class simply maps the right Row representation
* given the decoded datatype.
*
* @param rowSchema schema associated with the row
* @param data decoded Data
* @param <T> decoded column types
* @param <Serializable> serialization
* @return a row instance with associated schema and data
* @see com.ning.metrics.action.hdfs.data.parser.RowSerializer
*/
public static <T extends Comparable, Serializable> Row getRow(RowSchema rowSchema, List<T> data) {
if (data.get(0) instanceof DataItem) {
return new RowThrift(rowSchema, (List<DataItem>) data);
} else if (data.get(0) instanceof JsonNode) {
return new RowSmile(rowSchema, (List<JsonNodeComparable>) data);
} else {
return new RowText(rowSchema, (List<String>) data);
}
}Example 72
| Project: aerogear-unifiedpush-server-master File: RequestTransformerTest.java View source code |
@Test
public void shouldTransformSenderRequest() throws IOException {
//given
ObjectReader reader = JacksonUtils.getReader();
final String json = IOUtils.toString(getClass().getResourceAsStream("/message-format-100.json"));
StringBuilder current = new StringBuilder(json);
//when
final StringBuilder patched = requestTransformer.transform("/rest/sender", "100", current);
//then
final JsonNode patchedNode = reader.readTree(patched.toString());
JsonNode newNode = reader.readTree(getClass().getResourceAsStream("/new-message-format.json"));
assertEquals(newNode, patchedNode);
}Example 73
| Project: agorava-facebook-master File: TagListDeserializer.java View source code |
@SuppressWarnings("unchecked")
@Override
public List<Tag> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectMapper mapper = BeanResolver.getInstance().resolve(ObjectMapper.class);
jp.setCodec(mapper);
if (jp.hasCurrentToken()) {
JsonNode dataNode = (JsonNode) jp.readValueAs(JsonNode.class).get("data");
return (List<Tag>) mapper.reader(new TypeReference<List<Tag>>() {
}).readValue(dataNode);
}
return null;
}Example 74
| Project: agorava-linkedin-master File: RecommendationsListDeserializer.java View source code |
@Override
public List<Recommendation> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectMapper mapper = BeanResolver.getInstance().resolve(ObjectMapper.class);
jp.setCodec(mapper);
if (jp.hasCurrentToken()) {
JsonNode dataNode = jp.readValueAs(JsonNode.class).get("values");
if (dataNode != null) {
return mapper.reader(new TypeReference<List<Recommendation>>() {
}).readValue(dataNode);
}
}
return null;
}Example 75
| Project: agorava-twitter-master File: SimilarPlacesDeserializer.java View source code |
@Override
public SimilarPlacesResponse deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectMapper mapper = BeanResolver.getInstance().resolve(ObjectMapper.class);
jp.setCodec(mapper);
JsonNode node = jp.readValueAs(JsonNode.class);
JsonNode resultNode = node.get("result");
String token = resultNode.get("token").textValue();
JsonNode placesNode = resultNode.get("places");
@SuppressWarnings("unchecked") List<Place> places = (List<Place>) mapper.reader(new TypeReference<List<Place>>() {
}).readValue(placesNode);
return new SimilarPlacesResponse(places, token);
}Example 76
| Project: aincc-adventure-master File: OpenTraditionalMartInfo.java View source code |
@Override
public void parse() throws Exception {
infos = new ArrayList<TraditionalMartInfo>();
JSonManager manager = JSonManager.getInstance();
JsonNode content = manager.getNode(response);
JsonNode root = content.findPath(OpenAPI.TRADITIONAL_MART_INFO.getServiceName());
Iterator<Entry<String, JsonNode>> it = root.fields();
while (it.hasNext()) {
Entry<String, JsonNode> entry = it.next();
String rowId = entry.getKey();
JsonNode row = entry.getValue();
// Logger.v("row = " + rowId + "\n" + row.toString());
TraditionalMartInfo info = (TraditionalMartInfo) manager.deserialize(row.toString(), TraditionalMartInfo.class);
info.rowId = rowId;
infos.add(info);
}
}Example 77
| Project: alien4cloud-master File: AbstractFieldValueDiscriminatorPolymorphicDeserializer.java View source code |
protected T deserializeAfterRead(JsonParser jp, DeserializationContext ctxt, ObjectMapper mapper, ObjectNode root) throws JsonProcessingException {
Class<? extends T> parameterClass = null;
Iterator<Map.Entry<String, JsonNode>> elementsIterator = root.fields();
while (elementsIterator.hasNext()) {
Map.Entry<String, JsonNode> element = elementsIterator.next();
String name = element.getKey();
if (propertyDiscriminatorName.equals(name)) {
String value = element.getValue().asText();
if (registry.containsKey(value)) {
parameterClass = registry.get(value);
break;
}
}
}
if (parameterClass == null) {
return null;
}
return mapper.treeToValue(root, parameterClass);
}Example 78
| Project: alto-master File: EndpointpropertyRouteChecker.java View source code |
public static JsonNode checkJsonSyntax(String content) { JsonNode jsonContent; ObjectMapper mapper = new ObjectMapper(); try { jsonContent = mapper.readTree(content); } catch (IOException e) { throw new AltoErrorSyntax(); } if (null == jsonContent) { throw new AltoErrorSyntax(); } else if (jsonContent.isNull()) { throw new AltoErrorMissingField(AltoNorthboundRouteEndpointproperty.FIELD_PROPERTIES); } else { return jsonContent; } }
Example 79
| Project: android-contentprovider-generator-master File: JsonEnumValueDeserializer.java View source code |
@Override
public JsonEnumValue deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
JsonEnumValue res = new JsonEnumValue();
if (node.isObject()) {
Map.Entry<String, JsonNode> entry = node.fields().next();
res.name = entry.getKey();
res.documentation = entry.getValue().asText();
} else {
res.name = node.asText();
}
return res;
}Example 80
| Project: armeria-master File: MediaTypeJsonDeserializer.java View source code |
@Override
public MediaType deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
final JsonNode tree = p.getCodec().readTree(p);
if (!tree.isTextual()) {
ctx.reportMappingException("media type must be a string.");
return null;
}
final String textValue = tree.textValue();
try {
return MediaType.parse(textValue);
} catch (IllegalArgumentException unused) {
ctx.reportMappingException("malformed media type: " + textValue);
return null;
}
}Example 81
| Project: assertj-swagger-master File: Swagger20Parser.java View source code |
private static Swagger convertToSwagger(String data) throws IOException {
ObjectMapper mapper;
if (data.trim().startsWith("{")) {
mapper = Json.mapper();
} else {
mapper = Yaml.mapper();
}
JsonNode rootNode = mapper.readTree(data);
// must have swagger node set
JsonNode swaggerNode = rootNode.get("swagger");
if (swaggerNode == null) {
throw new IllegalArgumentException("Swagger String has an invalid format.");
} else {
return mapper.convertValue(rootNode, Swagger.class);
}
}Example 82
| Project: auth0-java-master File: UsersPageDeserializer.java View source code |
@Override
public UsersPage deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
JsonNode node = p.getCodec().readTree(p);
ObjectMapper mapper = new ObjectMapper();
if (node.isArray()) {
return new UsersPage(getArrayElements((ArrayNode) node, mapper));
}
Integer start = getIntegerValue(node.get("start"));
Integer length = getIntegerValue(node.get("length"));
Integer total = getIntegerValue(node.get("total"));
Integer limit = getIntegerValue(node.get("limit"));
ArrayNode array = (ArrayNode) node.get("users");
return new UsersPage(start, length, total, limit, getArrayElements(array, mapper));
}Example 83
| Project: avaje-ebeanorm-examples-master File: SimpleDocWithJsonNodeTest.java View source code |
@Test
public void test() throws IOException {
ObjectMapper mapper = new ObjectMapper();
String rawJson = "{\"docName\":\"rob doc\", \"docScore\":234}";
JsonNode jsonNode = mapper.readTree(rawJson);
SimpleDocUsingJsonNode doc = new SimpleDocUsingJsonNode();
doc.setName("doc1");
doc.setContent(jsonNode);
doc.save();
String fullJson = Ebean.json().toJson(doc);
SimpleDocUsingJsonNode doc2 = Ebean.json().toBean(SimpleDocUsingJsonNode.class, fullJson);
assertEquals(doc.getId(), doc2.getId());
assertEquals(doc.getName(), doc2.getName());
assertEquals(doc.getVersion(), doc2.getVersion());
assertEquals(doc.getContent().toString(), doc2.getContent().toString());
SimpleDocUsingJsonNode doc3 = Ebean.find(SimpleDocUsingJsonNode.class, doc.getId());
assertEquals(doc.getId(), doc3.getId());
assertEquals(doc.getName(), doc3.getName());
assertEquals(doc.getVersion(), doc3.getVersion());
assertEquals(doc.getContent().toString(), doc3.getContent().toString());
}Example 84
| Project: avaje-ebeanorm-master File: SimpleDocWithJsonNodeTest.java View source code |
@Test
public void test() throws IOException {
ObjectMapper mapper = new ObjectMapper();
String rawJson = "{\"docName\":\"rob doc\", \"docScore\":234}";
JsonNode jsonNode = mapper.readTree(rawJson);
SimpleDocUsingJsonNode doc = new SimpleDocUsingJsonNode();
doc.setName("doc1");
doc.setContent(jsonNode);
doc.save();
String fullJson = Ebean.json().toJson(doc);
SimpleDocUsingJsonNode doc2 = Ebean.json().toBean(SimpleDocUsingJsonNode.class, fullJson);
assertEquals(doc.getId(), doc2.getId());
assertEquals(doc.getName(), doc2.getName());
assertEquals(doc.getVersion(), doc2.getVersion());
assertEquals(doc.getContent().toString(), doc2.getContent().toString());
SimpleDocUsingJsonNode doc3 = Ebean.find(SimpleDocUsingJsonNode.class, doc.getId());
assertEquals(doc.getId(), doc3.getId());
assertEquals(doc.getName(), doc3.getName());
assertEquals(doc.getVersion(), doc3.getVersion());
assertEquals(doc.getContent().toString(), doc3.getContent().toString());
}Example 85
| Project: aws-dynamodb-mars-json-demo-master File: DynamoDBSolWorkerTest.java View source code |
private void testParseSol(final String file, final String expectedFile) {
try {
final JsonNode sol = mapper.readTree(new File(file));
final ArrayNode expected = (ArrayNode) mapper.readTree(new File(expectedFile));
final ArrayNode result = DynamoDBSolWorker.getImages(sol);
assertEquals(expected, result);
} catch (final IOException e) {
fail(e.getMessage());
}
}Example 86
| Project: Baragon-master File: MergingConfigProvider.java View source code |
@Override
public InputStream open(String path) throws IOException {
JsonNode originalNode = readFromPath(defaultConfigPath);
JsonNode overrideNode = readFromPath(path);
if (originalNode.isObject() && overrideNode.isObject()) {
ObjectNode original = (ObjectNode) originalNode;
ObjectNode override = (ObjectNode) overrideNode;
merge(original, override);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
objectMapper.writeTree(yamlFactory.createGenerator(outputStream), original);
return new ByteArrayInputStream(outputStream.toByteArray());
} else {
throw new IllegalArgumentException("Both configuration files must be objects");
}
}Example 87
| Project: belladati-sdk-java-master File: CachedListImpl.java View source code |
@Override
public CachedList<T> load() {
data.clear();
JsonNode json = service.getAsJson(uri);
if (json.get(field) instanceof ArrayNode) {
ArrayNode nodes = (ArrayNode) json.get(field);
for (JsonNode node : nodes) {
try {
data.add(parse(service, node));
} catch (ParseException e) {
}
}
}
isLoaded = true;
return this;
}Example 88
| Project: betfair-master File: TestClass.java View source code |
// TODO: how to process wrong session token - exception or errorCode
private static String getSessionToken() {
JsonNode jsonNode = null;
String sessionToken = null;
try {
String sessionResponse = null;
if ((sessionResponse = HttpClientSSO.getSessionTokenResponse()) != null) {
jsonNode = om.readTree(sessionResponse);
sessionToken = jsonNode.get(SESSION_TOKEN).toString();
log.info("Session token: {}", sessionToken);
} else {
log.error("Getting null session token from BetFair");
}
} catch (IOException e) {
log.error("Exception while processing session token: {}", e);
}
return sessionToken;
}Example 89
| Project: BioSolr-master File: YamlConfigurationLoader.java View source code |
@Override
public IndexerConfiguration loadConfiguration() throws IOException {
FileReader reader = new FileReader(configFile);
final JsonNode node = mapper.readTree(yamlFactory.createParser(reader));
final IndexerConfiguration config = mapper.readValue(new TreeTraversingParser(node), IndexerConfiguration.class);
// Close the file reader
reader.close();
return config;
}Example 90
| Project: buck-master File: HasJsonField.java View source code |
@Override
public void describeMismatch(Object item, Description description) {
if (item instanceof JsonNode) {
JsonNode node = (JsonNode) item;
try {
description.appendText("was ").appendText(ObjectMappers.WRITER.withDefaultPrettyPrinter().writeValueAsString(node));
} catch (IOException e) {
super.describeMismatch(item, description);
}
} else {
super.describeMismatch(item, description);
}
}Example 91
| Project: c2g-master File: LocationDeserializer.java View source code |
@Override
public Location deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
int id = (Integer) ((IntNode) node.get("locationId")).numberValue();
String countryCode = node.get("countryCode").asText();
String defaultLanguage = node.get("defaultLanguage").asText();
Locale locale = new Locale.Builder().setLanguage(defaultLanguage).setRegion(countryCode).build();
String name = node.get("locationName").asText();
JsonNode mapSection = node.get("mapSection");
Coordinates center = new Coordinates(mapSection.get("center").get("latitude").asDouble(), mapSection.get("center").get("longitude").asDouble());
Coordinates lowerRight = new Coordinates(mapSection.get("lowerRight").get("latitude").asDouble(), mapSection.get("lowerRight").get("longitude").asDouble());
Coordinates upperLeft = new Coordinates(mapSection.get("upperLeft").get("latitude").asDouble(), mapSection.get("upperLeft").get("longitude").asDouble());
TimeZone timezone = TimeZone.getTimeZone(node.get("timezone").asText());
return new Location(id, locale, name, center, lowerRight, upperLeft, timezone);
}Example 92
| Project: CampusFeedv2-master File: ScraperHandler.java View source code |
public static Result scrapedPage() {
JsonNode request = request().body().asJson();
// get all data
String url = request.get("url").textValue();
String url_decoded = null;
try {
url_decoded = URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return internalServerError();
}
int event_id = EventManager.createFromScrapedPage(request);
if (event_id == -1) {
return internalServerError();
} else {
try (Connection conn = DB.getConnection()) {
PreparedStatement stmt = conn.prepareStatement("INSERT INTO CampusFeed.Scraper (scrape_url,event_id) VALUES (?,?)");
stmt.setString(1, url_decoded);
stmt.setInt(2, event_id);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return internalServerError();
}
return ok("success");
}
}Example 93
| Project: cas-master File: X509CertificateCredentialJsonDeserializer.java View source code |
@Override
public X509CertificateCredential deserialize(final JsonParser jp, final DeserializationContext deserializationContext) throws IOException {
final ObjectCodec oc = jp.getCodec();
final JsonNode node = oc.readTree(jp);
final List<X509Certificate> certs = new ArrayList<>();
node.findValues("certificates").forEach( n -> {
final String cert = n.get(0).textValue();
final byte[] data = EncodingUtils.decodeBase64(cert);
certs.add(CertUtils.readCertificate(new InputStreamResource(new ByteArrayInputStream(data))));
});
final X509CertificateCredential c = new X509CertificateCredential(certs.toArray(new X509Certificate[] {}));
return c;
}Example 94
| Project: cassandra-mesos-master File: SeedManagerTest.java View source code |
@Before
public void before() {
InMemoryState state = new InMemoryState();
PersistedCassandraFrameworkConfiguration config = new PersistedCassandraFrameworkConfiguration(state, "name", 60, 30, "2.1", 0.5, 1024, 1024, 512, 1, 1, "role", "./backup", ".", false, true, "RACK1", "DC1", Arrays.asList(ExternalDc.newBuilder().setName("dc").setUrl("http://dc").build()), "name");
seedManager = new SeedManager(config, new ObjectMapper(), new SystemClock()) {
@Override
@Nullable
protected JsonNode fetchJson(@NotNull final String url) {
try {
return new ObjectMapper().readTree(jsonResponse);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
};
}Example 95
| Project: coinbase-java-master File: MoneyDeserializer.java View source code |
@Override
public Money deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
Money result = null;
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
String currency = null;
String amount = null;
Long cents = null;
if (node.has("currency")) {
currency = node.get("currency").textValue();
} else if (node.has("currency_iso")) {
currency = node.get("currency_iso").textValue();
}
if (node.has("amount")) {
amount = node.get("amount").textValue();
} else if (node.has("cents")) {
cents = node.get("cents").longValue();
}
if (currency == null || (amount == null && cents == null)) {
throw new JsonParseException("Wrong format for Money", jsonParser.getCurrentLocation());
}
try {
if (amount != null) {
result = Money.of(CurrencyUnit.of(currency), new BigDecimal(amount));
} else {
result = Money.ofMinor(CurrencyUnit.of(currency), cents);
}
} catch (Exception ex) {
throw new JsonParseException("Could not construct Money from arguments", jsonParser.getCurrentLocation(), ex);
}
return result;
}Example 96
| Project: dddlib-master File: YmlParser.java View source code |
@Override
public Set<ClassDefinition> parseReader(Reader in) {
final JsonNode node;
try {
node = objectMapper.readTree(yamlFactory.createParser(in));
PackageDefinition packageDefinition = objectMapper.readValue(new TreeTraversingParser(node), PackageDefinition.class);
return toClassDefinitions(packageDefinition);
} catch (IOException e) {
throw new ParsingException("Cannot parse reader!");
}
}Example 97
| Project: degraphmalizer-master File: JSONUtilities.java View source code |
public static ID fromJSON(JsonNode n) {
if (!n.isArray())
return null;
final ArrayNode a = (ArrayNode) n;
final String index = a.get(0).textValue();
final String type = a.get(1).textValue();
final String id = a.get(2).textValue();
final long version = a.get(3).longValue();
return new ID(index, type, id, version);
}Example 98
| Project: dev-search-master File: StashJsonParser.java View source code |
public List<StashProject> extractStashProjects(String jsonString) {
List<StashProject> stashObjects = new ArrayList<>();
try {
JsonNode valuesNode = mapper.readTree(jsonString).get("values");
Iterator<JsonNode> iter = valuesNode.elements();
while (iter.hasNext()) {
JsonNode valNode = iter.next();
stashObjects.add(new StashProject(getString(valNode, "key"), getString(valNode, "name")));
}
} catch (Exception e) {
System.err.println("dataType: " + "project" + " jsonString: " + jsonString);
Throwables.propagate(e);
}
return stashObjects;
}Example 99
| Project: docker-java-master File: JSONSamples.java View source code |
/**
* Same as {@link JSONTestHelper#testRoundTrip(java.lang.Object, java.lang.Class)}
* but via {@link TypeReference}
*/
public static <TClass> TClass testRoundTrip(TClass item, JavaType type) throws IOException, AssertionError {
ObjectMapper mapper = new ObjectMapper();
String serialized1 = mapper.writeValueAsString(item);
JsonNode json1 = mapper.readTree(serialized1);
TClass deserialized1 = mapper.readValue(serialized1, type);
String serialized2 = mapper.writeValueAsString(deserialized1);
JsonNode json2 = mapper.readTree(serialized2);
TClass deserialized2 = mapper.readValue(serialized2, type);
assertEquals(json2, json1, "JSONs must be equal after the second roundtrip");
assertEquals(deserialized2, deserialized2, "Objects must be equal after the second roundtrip");
assertNotSame(deserialized2, deserialized1, "Objects must be not the same");
return deserialized2;
}Example 100
| Project: droidtowers-master File: JacksonTransformer.java View source code |
@SuppressWarnings("unchecked")
@Override
public byte[] transform(Class<? extends JacksonTransformationScript> transformationClass, ByteArrayInputStream input) {
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode jsonNode = mapper.readValue(input, JsonNode.class);
Gdx.app.debug(TAG, "Executing migration: " + transformationClass.getSimpleName());
JacksonTransformationScript transformation = transformationClass.newInstance();
transformation.process(jsonNode, fileName);
return mapper.writeValueAsBytes(jsonNode);
} catch (Exception e) {
throw new RuntimeException("Unable to transform data using transformationClass = " + transformationClass, e);
}
}Example 101
| Project: ebean-master File: TestJsonNodeBlob.java View source code |
@Test
public void testInsertUpdateDelete() throws IOException {
String s0 = "{\"docId\":18,\"contentId\":\"asd\",\"active\":true,\"contentType\":\"pg-hello\",\"content\":{\"name\":\"rob\",\"age\":45}}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode content = objectMapper.readTree(s0);
EBasicJsonNodeBlob bean = new EBasicJsonNodeBlob();
bean.setName("one");
bean.setContent(content);
Ebean.save(bean);
EBasicJsonNodeBlob bean1 = Ebean.find(EBasicJsonNodeBlob.class, bean.getId());
assertEquals(bean.getId(), bean1.getId());
assertEquals(bean.getName(), bean1.getName());
assertEquals(bean.getContent().path("contentType").asText(), bean1.getContent().path("contentType").asText());
assertEquals(18L, bean1.getContent().get("docId").asLong());
}