Java Examples for com.fasterxml.jackson.databind.ObjectMapper
The following java examples will help you to understand the usage of com.fasterxml.jackson.databind.ObjectMapper. 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: geojson-jackson-master File: LngLatAltDeserializerTest.java View source code |
@Test
public void deserializeMongoLngLatAlt() throws Exception {
LngLatAlt lngLatAlt = new LngLatAlt(10D, 15D, 5);
String lngLatAltJson = new ObjectMapper().writeValueAsString(lngLatAlt);
lngLatAltJson.replace("10.0", "\"10.0\"");
lngLatAltJson.replace("15.0", "\"15.0\"");
LngLatAlt lngLatAlt1 = new ObjectMapper().readValue(lngLatAltJson, LngLatAlt.class);
Assert.assertTrue(lngLatAlt.equals(lngLatAlt));
}Example 3
| Project: mozu-java-master File: ExtensionConfiguration.java View source code |
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
if (configuration == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
new com.fasterxml.jackson.databind.ObjectMapper().configure(com.fasterxml.jackson.core.JsonGenerator.Feature.AUTO_CLOSE_TARGET, false).writeValue(out, configuration);
}
}Example 4
| Project: sandboxes-master File: CreatePageTO_Test.java View source code |
@Test
public void ensureTransferObjectCanBeSerialized() throws Exception {
CreatePageTO to = new CreatePageTO.Builder().space("DEMO").title("Automation for the win").content("<p>I like the storage format.</p>").build();
String json = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(to);
assertThat(json, CoreMatchers.notNullValue());
}Example 5
| Project: AIDR-master File: FasterXmlWrapper.java View source code |
public static ObjectMapper getObjectMapper() { try { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return objectMapper; } catch (Exception e) { logger.error("Exception in FasterXmlWrapper " + e.getStackTrace()); return null; } }
Example 6
| Project: apollo-datastore-rest-master File: SessionHandlingExceptionMapper.java View source code |
@Override
public Response toResponse(SessionHandlingException e) {
String json = null;
ObjectMapper mapper = new ObjectMapper();
try {
json = mapper.writeValueAsString(new ErrorJson(e.getError()));
} catch (JsonProcessingException e1) {
e1.printStackTrace();
}
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON).entity(json).build();
}Example 7
| Project: ceeql-master File: CeeqlMessage.java View source code |
@Override
public String toJson() {
CeeqlMessageDTO m = new CeeqlMessageDTO();
m.setMessageType("message");
m.setMessageSubType("Info");
m.setTimestamp(timestamp);
m.setMessage(message);
ArrayList<CeeqlMessageDTO> l = new ArrayList<>();
l.add(m);
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(l);
} catch (JsonProcessingException e) {
return "";
}
}Example 8
| Project: dev-search-master File: ProjectsRestHandler.java View source code |
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
try {
ObjectMapper mapper = new ObjectMapper();
channel.sendResponse(new BytesRestResponse(OK, mapper.writeValueAsString(indexService.findAllProjects(0, 10000))));
} catch (Exception e) {
logger.error("Failed to get projects", e);
channel.sendResponse(new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, e.getMessage()));
}
}Example 9
| Project: heroic-master File: TopKTest.java View source code |
@Test
public void serialization() throws Exception {
final ObjectMapper mapper = m.json();
assertEquals(new TopK(1, Optional.empty()), mapper.readValue(m.jsonObject().put("type", TopK.NAME).put("k", 1).string(), Aggregation.class));
assertEquals(new TopKInstance(1), mapper.readValue(m.jsonObject().put("type", TopK.NAME).put("k", 1).string(), AggregationInstance.class));
}Example 10
| Project: jackson-databind-master File: TestSubtypes1311.java View source code |
/*
/**********************************************************
/* Unit tests
/**********************************************************
*/
// [databind#1311]
public void testSubtypeAssignmentCheck() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.registerSubtypes(Factory1311ImplA.class, Factory1311ImplB.class);
Factory1311ImplB result = mapper.readValue("{\"type\":\"implB\"}", Factory1311ImplB.class);
assertNotNull(result);
assertEquals(Factory1311ImplB.class, result.getClass());
}Example 11
| Project: jackson-datatype-guava-master File: ScalarTypesTest.java View source code |
public void testInternetDomainNameDeserialization() throws Exception {
final String INPUT = "google.com";
// InternetDomainName name = MAPPER.readValue(quote(INPUT), InternetDomainName.class);
InternetDomainName name = new ObjectMapper().readValue(quote(INPUT), InternetDomainName.class);
assertNotNull(name);
assertEquals(INPUT, name.toString());
}Example 12
| Project: jive-utils-master File: TenantIdTest.java View source code |
@Test
public void testSerializeDeserialize() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
TenantId tenantId = new TenantId("foobar");
String tenantIdJson = objectMapper.writeValueAsString(tenantId);
TenantId tenantIdFromJson = objectMapper.readValue(tenantIdJson, TenantId.class);
assertEquals(tenantIdFromJson, tenantId);
}Example 13
| Project: lumify-master File: ObjectMapperFactory.java View source code |
public static ObjectMapper getInstance() { if (mapper == null) { mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } return mapper; }
Example 14
| Project: simba-os-master File: ESAPIDeserializerTest.java View source code |
@Test
public void becauseSimbaEncodesToHTMLUsingESAPI_JacksonShouldDecodeWhenDeserializing() throws Exception {
String esapiEncodedString = "bruce@wayneindustries.com";
TestObject testObject = new ObjectMapper().readValue("{" + "\"esapiDeserializerAnnotatedString\":\"" + esapiEncodedString + "\"" + "," + "\"nonAnnotatedString\":\"" + esapiEncodedString + "\"" + "}", TestObject.class);
assertThat(testObject.getEsapiDeserializerAnnotatedString()).isEqualTo("bruce@wayneindustries.com");
assertThat(testObject.getNonAnnotatedString()).isEqualTo("bruce@wayneindustries.com");
}Example 15
| Project: spring-cloud-example-master File: ErrorUtil.java View source code |
public static String appendError(String message, Error error) {
FullError wrap = new FullError();
wrap.setMessage(message);
wrap.setError(error);
ObjectMapper mapper = new ObjectMapper();
String jsonString = message;
try {
jsonString = mapper.writeValueAsString(wrap);
} catch (Exception e) {
log.error("exceptionWithErrorObjectTranslateFail,{}", e);
}
return jsonString;
}Example 16
| Project: spring-integration-master File: JacksonJsonUtils.java View source code |
/**
* Return an {@link com.fasterxml.jackson.databind.ObjectMapper} if available,
* supplied with Message specific serializers and deserializers.
* Also configured to store typo info in the {@code @class} property.
* @return the mapper.
* @throws IllegalStateException if an implementation is not available.
* @since 4.3.10
*/
public static com.fasterxml.jackson.databind.ObjectMapper messagingAwareMapper() {
if (JacksonPresent.isJackson2Present()) {
ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
GenericMessageJacksonDeserializer genericMessageDeserializer = new GenericMessageJacksonDeserializer();
genericMessageDeserializer.setMapper(mapper);
ErrorMessageJacksonDeserializer errorMessageDeserializer = new ErrorMessageJacksonDeserializer();
errorMessageDeserializer.setMapper(mapper);
AdviceMessageJacksonDeserializer adviceMessageDeserializer = new AdviceMessageJacksonDeserializer();
adviceMessageDeserializer.setMapper(mapper);
MutableMessageJacksonDeserializer mutableMessageDeserializer = new MutableMessageJacksonDeserializer();
mutableMessageDeserializer.setMapper(mapper);
mapper.registerModule(new SimpleModule().addSerializer(new MessageHeadersJacksonSerializer()).addDeserializer(GenericMessage.class, genericMessageDeserializer).addDeserializer(ErrorMessage.class, errorMessageDeserializer).addDeserializer(AdviceMessage.class, adviceMessageDeserializer).addDeserializer(MutableMessage.class, mutableMessageDeserializer));
return mapper;
} else {
throw new IllegalStateException("No jackson-databind.jar is present in the classpath.");
}
}Example 17
| Project: swagger-parser-master File: ApiDeclarationReader.java View source code |
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
ApiDeclaration apiDeclaration = objectMapper.readValue(new URL("http://petstore.swagger.io/api/api-docs/store"), ApiDeclaration.class);
System.out.println(apiDeclaration);
}Example 18
| Project: trickl-graph-master File: JsonConfiguration.java View source code |
@Bean public ObjectMapper getObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); AnnotationIntrospector annotationIntrospector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); objectMapper.setAnnotationIntrospector(annotationIntrospector); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); return objectMapper; }
Example 19
| Project: XChange-master File: QuoineOrderResponseJSONTest.java View source code |
@Test
public void testUnmarshal() throws IOException {
// Read in the JSON from the example resources
InputStream is = QuoineOrderResponseJSONTest.class.getResourceAsStream("/trade/example-order-response.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
QuoineOrderResponse qoineOrderResponse = mapper.readValue(is, QuoineOrderResponse.class);
// Verify that the example data was unmarshalled correctly
assertThat(qoineOrderResponse.getId()).isEqualTo("52351");
assertThat(qoineOrderResponse.getQuantity()).isEqualTo(new BigDecimal(".1"));
assertThat(qoineOrderResponse.getCreatedAt()).isEqualTo("2015-04-25T08:20:40+00:00");
assertThat(qoineOrderResponse.getOrderType()).isEqualTo("limit");
}Example 20
| Project: muikku-master File: AbstractRESTTest.java View source code |
@Before
public void setupRestAssured() throws JsonProcessingException {
RestAssured.baseURI = getAppUrl(true) + "/rest";
RestAssured.port = getPortHttps();
RestAssured.authentication = certificate(getKeystoreFile(), getKeystorePass());
RestAssured.config = RestAssuredConfig.config().objectMapperConfig(ObjectMapperConfig.objectMapperConfig().jackson2ObjectMapperFactory(new Jackson2ObjectMapperFactory() {
@SuppressWarnings("rawtypes")
@Override
public com.fasterxml.jackson.databind.ObjectMapper create(Class cls, String charset) {
com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
objectMapper.registerModule(new JSR310Module());
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
}));
}Example 21
| Project: 101simplejava-master File: Unparsing.java View source code |
/**
* Write the JsonTree root to file
*
* @param root
* @param file
*/
public static void unparse(JsonNode root, File file) {
ObjectMapper mapper = new ObjectMapper();
PrettyPrinter printer = new DefaultPrettyPrinter();
ObjectWriter writer = mapper.writer(printer);
file.getParentFile().mkdirs();
try {
writer.writeValue(file, root);
} catch (IOException e) {
e.printStackTrace();
}
}Example 22
| Project: auto-matter-master File: ComplexGenericJacksonExample.java View source code |
public static void main(final String... args) throws IOException {
// Register the AutoMatterModule to handle deserialization
ObjectMapper mapper = new ObjectMapper().registerModule(new AutoMatterModule());
ComplexGenericFoobar<String, Integer, List<Integer>, ComparableList<Integer>> foobar = new ComplexGenericFoobarBuilder<String, Integer, List<Integer>, ComparableList<Integer>>().foo("foo").bar(17).baz(asList(13, 4711)).quux(ComparableList.of(1, 2, 3)).name("generics").build();
String json = mapper.writeValueAsString(foobar);
out.println("json: " + json);
ComplexGenericFoobar<String, Integer, List<Integer>, ComparableList<Integer>> parsed = mapper.readValue(json, new TypeReference<ComplexGenericFoobar<String, Integer, List<Integer>, ComparableList<Integer>>>() {
});
out.println("parsed: " + parsed);
out.println("equals: " + foobar.equals(parsed));
}Example 23
| Project: bootique-master File: JsonNodeYamlParserTest.java View source code |
@Test
public void testApply() {
InputStream in = new ByteArrayInputStream("a: b\nb: c".getBytes());
ObjectMapper mapper = new ObjectMapper();
Optional<JsonNode> node = new JsonNodeYamlParser(mapper).apply(in);
assertTrue(node.isPresent());
assertEquals("b", node.get().get("a").asText());
assertEquals("c", node.get().get("b").asText());
}Example 24
| Project: checklistbank-master File: ImporterServiceIT.java View source code |
/**
* Make sure messages are all registered and the service starts up fine.
*/
@Test
public void testStartUp() throws Exception {
File neoTmp = FileUtils.createTempDir();
neoTmp.deleteOnExit();
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
ImporterConfiguration cfg = mapper.readValue(Resources.getResource("cfg-importer.yaml"), ImporterConfiguration.class);
cfg.neo.neoRepository = neoTmp;
ImporterService imp = new ImporterService(cfg);
imp.startUp();
}Example 25
| Project: civilization-boardgame-rest-master File: TurnKeySerializer.java View source code |
@Override
public void serialize(TurnKey value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
if (null == value) {
throw new IOException("Could not serialize object to json, input object to serialize is null");
}
StringWriter writer = new StringWriter();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(writer, value);
gen.writeFieldName(writer.toString());
}Example 26
| Project: common_utils-master File: IpHelper.java View source code |
public static IpVo getLocalIp() {
HttpRequestBase build = HttpBuilder.newBuilder().url("ipinfo.io/json").build();
try {
InputStream inputStream = HttpAccess.executeAndGetInputStream(HttpAccess.getClient(), build);
ObjectMapper objectMapper = new ObjectMapper();
IpVo ipVo = objectMapper.readValue(inputStream, IpVo.class);
return ipVo;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}Example 27
| Project: crawljax-master File: IsValidJson.java View source code |
/**
* @return a {@link Matcher} that checks if the given {@link File} contains a valid JSON object.
*/
@Factory
public static <T> Matcher<File> isValidJson() {
return new TypeSafeMatcher<File>() {
@Override
public void describeTo(Description description) {
description.appendText("Valid JSON String");
}
@Override
protected boolean matchesSafely(File item) {
boolean valid = false;
try {
JsonParser parser = new ObjectMapper().getFactory().createParser(item);
while (parser.nextToken() != null) {
}
valid = true;
} catch (IOException e) {
throw new AssertionError(e);
}
return valid;
}
};
}Example 28
| Project: dip-master File: FlatJsonConverter.java View source code |
public static Map<String, Object> convertToMap(String json) {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = null;
// convert JSON string to Map
try {
map = mapper.readValue(json, new TypeReference<LinkedHashMap<String, Object>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
return map;
}Example 29
| Project: docker-java-master File: VersionTest.java View source code |
@Test
public void testSerDer1() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final JavaType type = mapper.getTypeFactory().uncheckedSimpleType(Version.class);
final Version version = testRoundTrip(RemoteApiVersion.VERSION_1_22, "/version/1.json", type);
assertThat(version, notNullValue());
assertThat(version.getVersion(), is("1.10.1"));
assertThat(version.getApiVersion(), is("1.22"));
assertThat(version.getGitCommit(), is("9e83765"));
assertThat(version.getGoVersion(), is("go1.5.3"));
assertThat(version.getOperatingSystem(), is("linux"));
assertThat(version.getArch(), is("amd64"));
assertThat(version.getKernelVersion(), is("4.1.17-boot2docker"));
assertThat(version.getBuildTime(), is("2016-02-11T20:39:58.688092588+00:00"));
}Example 30
| Project: Ektorp-master File: OpenCouchDbDocumentTest.java View source code |
@SuppressWarnings("unchecked")
@Test
public void testAnonymous() throws Exception {
ObjectMapper mapper = new ObjectMapper();
String orgJson = IOUtils.toString(getClass().getResourceAsStream("open_doc.json"), "UTF-8");
FlexDoc d = mapper.readValue(orgJson, FlexDoc.class);
assertEquals("doc_id", d.getId());
assertEquals("unknown", d.getAnonymous().get("mysteryStringField"));
assertEquals(12345, d.getAnonymous().get("mysteryIntegerField"));
Map<String, Object> mysteryObject = (Map<String, Object>) d.getAnonymous().get("mysteryObjectField");
assertEquals("foo", mysteryObject.get("nestedField1"));
assertEquals("bar", mysteryObject.get("nestedField2"));
List<String> mysteryList = (List<String>) d.getAnonymous().get("mysteryArrayField");
assertEquals(3, mysteryList.size());
assertEquals("a1", mysteryList.get(0));
String newJson = mapper.writeValueAsString(d);
assertTrue(JSONComparator.areEqual(newJson, orgJson));
}Example 31
| 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 32
| Project: geoserver-master File: Utils.java View source code |
public static KombuMessage toKombu(byte[] data) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"));
SimpleModule module = new SimpleModule();
module.addDeserializer(KombuSource.class, new KombuSourceDeserializer());
mapper.registerModule(module);
return mapper.readValue(data, KombuMessage.class);
}Example 33
| Project: jackson-datatype-hibernate-master File: ForceLazyLoadingTest.java View source code |
// [Issue#15]
@Test
public void testGetCustomerJson() throws Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnit");
try {
EntityManager em = emf.createEntityManager();
// false -> no forcing of lazy loading
ObjectMapper mapper = mapperWithModule(true);
Customer customer = em.find(Customer.class, 103);
assertFalse(Hibernate.isInitialized(customer.getPayments()));
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(customer);
// should force loading...
Set<Payment> payments = customer.getPayments();
/*
System.out.println("--- JSON ---");
System.out.println(json);
System.out.println("--- /JSON ---");
*/
assertTrue(Hibernate.isInitialized(payments));
// TODO: verify
assertNotNull(json);
Map<?, ?> stuff = mapper.readValue(json, Map.class);
assertTrue(stuff.containsKey("payments"));
assertTrue(stuff.containsKey("orders"));
assertNull(stuff.get("orderes"));
} finally {
emf.close();
}
}Example 34
| Project: janusz-master File: ConfigLoader.java View source code |
public static JanuszConfiguration load(String[] args) throws IOException {
File fileConfig = new File(args.length > 0 ? args[0] : "application.yaml");
if (!fileConfig.exists()) {
throw new JanuszException(new IllegalArgumentException(String.format("Config file %s does not exists in classpath", fileConfig.getName())));
}
return new ObjectMapper(new YAMLFactory()).readValue(fileConfig, JanuszConfiguration.class);
}Example 35
| Project: jerseyoauth2-master File: OAuth20TokenExtractorImpl.java View source code |
@SuppressWarnings("rawtypes")
@Override
public Token extract(String response) {
ObjectMapper mapper = new ObjectMapper();
try {
Map tokenMap = mapper.readValue(response, Map.class);
if (!tokenMap.containsKey("access_token")) {
throw new TokenExtractorException(response);
}
String accessToken = (String) tokenMap.get("access_token");
String refreshToken = (String) tokenMap.get("refresh_token");
String expiration = null;
if (tokenMap.containsKey("expires_in")) {
expiration = ((Integer) tokenMap.get("expires_in")).toString();
}
return new OAuth2Token(accessToken, refreshToken, expiration, response);
} catch (IOException e) {
throw new TokenExtractorException(response, e);
}
}Example 36
| Project: json-parsers-benchmark-master File: JacksonSerializerImpl.java View source code |
private ObjectMapper initMapper() { ObjectMapper m = new ObjectMapper().enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING).disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US); formatter.setTimeZone(TimeZone.getTimeZone("GMT")); m.setDateFormat(formatter); return m; }
Example 37
| Project: Leads-QueryProcessorM-master File: ObjectNodeTest.java View source code |
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
SQLQuery query = new SQLQuery("user", "location", "select * from atable", "SELECT");
String val = mapper.writeValueAsString(query);
JsonNode root = mapper.readTree(val);
((ObjectNode) root).put("state", String.valueOf(QueryState.COMPLETED));
System.out.println("node: " + root.toString());
} catch (Exception e) {
e.printStackTrace();
}
}Example 38
| 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 39
| Project: oerworldmap-master File: User.java View source code |
@Override
public String toString() {
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = null;
try {
json = ow.writeValueAsString(this);
} catch (JsonProcessingException e) {
System.err.println(String.format("Error while transforming user %s to JSON String.", email));
e.printStackTrace();
}
return json;
}Example 40
| Project: paasport-master File: ConfigLoader.java View source code |
public T getConfig() {
try {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
LOGGER.info(String.format("Loading config from: %s", configFileName));
return mapper.readValue(this.getClass().getClassLoader().getResourceAsStream(configFileName), configClass);
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 41
| Project: restx-master File: StdUserTest.java View source code |
@Test
public void should_serialize_deserialize() throws Exception {
ObjectMapper objectMapper = new ObjectMapper().registerModule(new GuavaModule());
String admin = objectMapper.writer().writeValueAsString(new StdUser("admin", ImmutableSet.<String>of("restx-admin")));
assertThat(admin).isEqualTo("{\"name\":\"admin\",\"roles\":[\"restx-admin\"]}");
StdUser u = objectMapper.reader().withType(StdUser.class).readValue(admin);
assertThat(u.getName()).isEqualTo("admin");
assertThat(u.getPrincipalRoles()).isEqualTo(ImmutableSet.<String>of("restx-admin"));
}Example 42
| Project: spring4-showcase-master File: AbstractClientTest.java View source code |
@Before
public void setUp() throws Exception {
//需è¦?æ·»åŠ jackson jar包
objectMapper = new ObjectMapper();
//需è¦?æ·»åŠ jaxb2实现(如xstream)
marshaller = new Jaxb2Marshaller();
marshaller.setPackagesToScan(new String[] { "com.sishuok" });
marshaller.afterPropertiesSet();
restTemplate = new RestTemplate();
}Example 43
| Project: swagger-core-master File: SwaggerTestBase.java View source code |
public static ObjectMapper mapper() { if (mapper == null) { mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } return mapper; }
Example 44
| 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 45
| Project: vivarium-master File: ServerNetworkModuleTest.java View source code |
@Test
@Category({ FastTest.class, UnitTest.class })
public void testConstruct() {
InboundNetworkListener a = new InboundNetworkListener();
ObjectMapper b = new ObjectMapper();
ServerNetworkModule networkModule = new ServerNetworkModule(a, b);
Tester.isNotNull("NetworkModule can be built", networkModule);
networkModule.sendMessage(UUID.randomUUID(), mock(Message.class));
}Example 46
| Project: whatscloud-android-master File: Singleton.java View source code |
public static ObjectMapper getJackson() { if (mMapper == null) { //--------------------------------- // Get Jackson instance //--------------------------------- mMapper = new ObjectMapper(); //--------------------------------- // Ignore unknown properties //--------------------------------- mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } return mMapper; }
Example 47
| Project: _Whydah-UserAdminService-master File: RoleRepresentationMapper.java View source code |
public static List<RoleRepresentation> fromJson(String roleJson) {
List<RoleRepresentation> roles = null;
try {
ObjectMapper mapper = new ObjectMapper();
roles = mapper.readValue(roleJson, new TypeReference<List<RoleRepresentation>>() {
});
} catch (JsonMappingException e) {
throw new IllegalArgumentException("Error mapping json for " + roleJson, e);
} catch (JsonParseException e) {
throw new IllegalArgumentException("Error parsing json for " + roleJson, e);
} catch (IOException e) {
throw new IllegalArgumentException("Error reading json for " + roleJson, e);
}
return roles;
}Example 48
| Project: pyramus-master File: AbstractRESTServiceTest.java View source code |
@Before
public void setupRestAssured() {
RestAssured.baseURI = getAppUrl(true) + "/1";
RestAssured.port = getPortHttps();
RestAssured.authentication = certificate(getKeystoreFile(), getKeystorePass());
RestAssured.config = RestAssuredConfig.config().objectMapperConfig(ObjectMapperConfig.objectMapperConfig().jackson2ObjectMapperFactory(new Jackson2ObjectMapperFactory() {
@SuppressWarnings("rawtypes")
@Override
public com.fasterxml.jackson.databind.ObjectMapper create(Class cls, String charset) {
com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
objectMapper.registerModule(new JSR310Module());
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
}));
}Example 49
| Project: ache-master File: KeepLinkRelevanceTargetClassifier.java View source code |
public TargetClassifier build(Path basePath, ObjectMapper yaml, JsonNode parameters) throws JsonProcessingException, IOException {
if (parameters != null) {
TargetClassifier wekaClassifier = new WekaTargetClassifier.Builder().build(basePath, yaml, parameters);
return new KeepLinkRelevanceTargetClassifier(wekaClassifier);
} else {
return new KeepLinkRelevanceTargetClassifier(null);
}
}Example 50
| Project: Acuitra-master File: ExtractTaggedEntityWordStage.java View source code |
@Override
public void execute() {
String taggedQuestion = getContext().getPreviousOutput(NamedEntityRecognitionStage.class.getName()).get(0);
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode rootNode = mapper.readTree(taggedQuestion);
setOutput(findTaggedWord(rootNode));
} catch (IOException e) {
throw new RuntimeException(e);
}
}Example 51
| Project: airlift-master File: JsonModule.java View source code |
@Override
public void configure(Binder binder) {
binder.disableCircularProxies();
// NOTE: this MUST NOT be a singleton because ObjectMappers are mutable. This means
// one component could reconfigure the mapper and break all other components
binder.bind(ObjectMapper.class).toProvider(ObjectMapperProvider.class);
binder.bind(JsonCodecFactory.class).in(Scopes.SINGLETON);
}Example 52
| Project: ameba-master File: JacksonUtils.java View source code |
/**
* <p>configFilterIntrospector.</p>
*
* @param mapper a {@link com.fasterxml.jackson.databind.ObjectMapper} object.
* @return a {@link com.fasterxml.jackson.databind.ObjectMapper} object.
*/
public static ObjectMapper configFilterIntrospector(final ObjectMapper mapper) {
final AnnotationIntrospector customIntrospector = mapper.getSerializationConfig().getAnnotationIntrospector();
// Set the custom (user) introspector to be the primary one.
return mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(customIntrospector, new JacksonAnnotationIntrospector() {
@Override
public Object findFilterId(final Annotated a) {
final Object filterId = super.findFilterId(a);
if (filterId != null) {
return filterId;
}
if (a instanceof AnnotatedMethod) {
final Method method = ((AnnotatedMethod) a).getAnnotated();
// Interested only in getters - trying to obtain "field" name from them.
if (ReflectionHelper.isGetter(method)) {
return ReflectionHelper.getPropertyName(method);
}
}
if (a instanceof AnnotatedField || a instanceof AnnotatedClass) {
return a.getName();
}
return null;
}
}));
}Example 53
| Project: amza-master File: AmzaSyncUIServiceInitializer.java View source code |
public AmzaSyncUIService initialize(SoyRenderer renderer, AmzaSyncSenders syncSenders, AmzaSyncStats stats, boolean senderEnabled, boolean receiverEnabled, ObjectMapper mapper) throws Exception {
return new AmzaSyncUIService(renderer, new HeaderRegion("soy.amza.chrome.headerRegion", renderer), new AmzaAdminRegion("soy.amza.page.adminRegion", renderer, stats, senderEnabled, receiverEnabled, syncSenders), new AmzaStatusRegion("soy.amza.page.statusRegion", renderer, new AmzaStatusFocusRegion("soy.amza.page.statusFocusRegion", renderer, syncSenders, mapper), syncSenders));
}Example 54
| Project: androGister-master File: SyncRequestWriter.java View source code |
public void syncFile(InputStream is, Writer out) throws IOException {
// Init Jackson
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
MappingJsonFactory jsonFactory = new MappingJsonFactory(mapper);
// Init Writer
final JsonGenerator jgen = jsonFactory.createGenerator(out);
jgen.writeStartObject();
// Close Json Writer
jgen.writeEndObject();
jgen.close();
}Example 55
| Project: android-atleap-master File: RetrofitHelper.java View source code |
public static RestAdapter.Builder createBaseRestAdapter(RestAdapter.Builder builder) {
if (builder == null)
builder = new RestAdapter.Builder();
builder.setConverter(new JacksonConverter(new ObjectMapper()));
if (BuildConfig.DEBUG) {
builder.setLogLevel(RestAdapter.LogLevel.FULL);
} else {
builder.setLogLevel(RestAdapter.LogLevel.NONE);
}
return builder;
}Example 56
| Project: anythingworks-master File: ClientJacksonJsonMarshallerFactory.java View source code |
@NotNull private static ObjectMapper makeDefaultMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); //disputable, very disputable for sending to the server. mapper.enable(SerializationFeature.INDENT_OUTPUT); //exclude null mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); //for Guava Optional: GuavaModule module = new GuavaModule(); mapper.registerModule(module); return mapper; }
Example 57
| 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 58
| 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 59
| Project: arquillian-cube-master File: GitHubUtil.java View source code |
public static LatestRepository consumeHttp(URL url) {
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
ObjectMapper mapper = new ObjectMapper();
LatestRepository latestRepository = mapper.readValue(connection.getInputStream(), LatestRepository.class);
return latestRepository;
} catch (IOException e) {
log.log(Level.WARNING, e.getMessage());
}
return null;
}Example 60
| Project: artifactory-plugin-master File: ArtifactoryDownloadUploadJsonTest.java View source code |
@Test
public void testReadJson() throws IOException {
InputStream stream = ArtifactoryDownloadUploadJsonTest.class.getClassLoader().getResourceAsStream("jsons/download.json");
String jsonStr = IOUtils.toString(stream);
ObjectMapper mapper = new ObjectMapper();
Spec downloadJson = mapper.readValue(jsonStr, Spec.class);
assertEquals("File pattern is incorrect", "my-repo/resolved.my", downloadJson.getFiles()[0].getPattern());
String expectedAql = "{\"repo\":\"my-repo\",\"$or\":[{\"$and\":[{\"path\":{\"$match\":\"*\"},\"name\":{\"$match\":\"*.zip\"}}]}]}";
assertEquals("Aql is incorrect", expectedAql, downloadJson.getFiles()[1].getAql());
assertEquals("File target is incorrect", "my-repo/by-pattern/", downloadJson.getFiles()[0].getTarget());
assertNull(downloadJson.getFiles()[0].getAql());
assertNull(downloadJson.getFiles()[1].getPattern());
}Example 61
| Project: auth0-java-master File: Telemetry.java View source code |
public String getValue() {
Map<String, String> values = new HashMap<>();
if (name != null) {
values.put(NAME_KEY, name);
}
if (version != null) {
values.put(VERSION_KEY, version);
}
if (values.isEmpty()) {
return null;
}
String urlSafe = null;
try {
String json = new ObjectMapper().writeValueAsString(values);
urlSafe = Base64.encodeBase64URLSafeString(json.getBytes());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return urlSafe;
}Example 62
| Project: AXON-E-Tools-master File: RestFunctionServletRequestImpl.java View source code |
/* (non-Javadoc) * @see de.axone.web.rest.RFSRI#mapper() */ @Override public ObjectMapper mapper() { if (mapper == null) { mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // JS uses unix timestamps!!! //mapper.configure( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false ); } return mapper; }
Example 63
| Project: beakerx-master File: ResultsDeserializerTest.java View source code |
@Test
public void deserialize_resultObjectHasPayload() throws Exception {
//given
boolean payload = true;
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree("{\"type\":\"Results\",\"payload\":\"" + payload + "\"}");
ResultsDeserializer deserializer = new ResultsDeserializer(new BasicObjectSerializer());
//when
Boolean result = (Boolean) deserializer.deserialize(actualObj, mapper);
//then
Assertions.assertThat(result).isEqualTo(payload);
}Example 64
| Project: bees-shop-master File: ConfigService.java View source code |
public ModelMap getConfig(ModelMap model) {
Map<String, Object> config = new HashMap<String, Object>();
List<Config> configList = findAll(" ");
for (Config configItem : configList) {
if (configItem.getType() != null && configItem.getType().equals("map")) {
try {
HashMap<String, Object> result = new ObjectMapper().readValue(configItem.getValue(), HashMap.class);
config.put(configItem.getName(), result);
} catch (IOException e) {
e.printStackTrace();
}
} else {
config.put(configItem.getName(), configItem.getValue());
}
}
model.addAttribute("config", config);
return model;
}Example 65
| Project: BETaaS_Platform-Tools-master File: MessageBuilder.java View source code |
public Message returnMessageObject(String jsonMessage) {
// can reuse, share globally
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(jsonMessage, Message.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}Example 66
| Project: blobkeeper-master File: FileModule.java View source code |
@Provides
@Singleton
public Map<Integer, DiskConfiguration> diskConfigurations(ObjectMapper objectMapper, @Named("blobkeeper.disk.configuration") String value) {
try {
List<DiskConfiguration> config = objectMapper.readValue(value, new TypeReference<List<DiskConfiguration>>() {
});
return config.stream().collect(toImmutableMap(DiskConfiguration::getDisk, identity()));
} catch (IOException e) {
log.error("Can't read disk configuration");
throw new IllegalArgumentException(e);
}
}Example 67
| Project: brooklyn-service-broker-master File: UserDefinedBlueprintPlanTest.java View source code |
@Test
public void testToBlueprint() throws JsonProcessingException {
UserDefinedBlueprintPlan plan = new UserDefinedBlueprintPlan("testId", "testName", "testDescription", ImmutableMap.of());
Map<?, ?> map = ImmutableMap.<Object, Object>of("name", "testUserDefinedService", "services", ImmutableList.of(ImmutableMap.of("type", "development.test.MyTestService")));
when(request.getParameters()).thenReturn((Map) map);
String result = plan.toBlueprint(null, "anyLocation", request);
ObjectMapper om = new ObjectMapper();
String expected = om.writeValueAsString(map);
assertEquals(expected, result);
}Example 68
| 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 69
| Project: coinbase-java-master File: ObjectMapperProvider.java View source code |
public static ObjectMapper createDefaultMapper() { final ObjectMapper result = new ObjectMapper(); result.setSerializationInclusion(Include.NON_NULL); result.configure(SerializationFeature.INDENT_OUTPUT, false); result.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); result.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); SimpleModule module = new SimpleModule(); module.addDeserializer(Money.class, new MoneyDeserializer()); module.addDeserializer(CurrencyUnit.class, new CurrencyUnitDeserializer()); module.addSerializer(CurrencyUnit.class, new CurrencyUnitSerializer()); result.registerModule(module); result.registerModule(new JodaModule()); return result; }
Example 70
| Project: Desktop-master File: MapModel.java View source code |
public String toJsonString() {
try {
final ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(this);
} catch (Exception e) {
return "";
}
//return "{\"id\":\""+id+"\",\"name\":\""+name+"\",\"revision\":\""+revision+"\",\"isReadonly\":\""+isReadonly+"\",\"root\":"+root.toJsonString()+"}";
}Example 71
| Project: droidtowers-master File: GenerateLicenseFileList.java View source code |
public static void main(String[] args) {
GdxNativesLoader.load();
addDirectoryToAssetManager("licenses/", ".txt");
try {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
new FileHandle("assets/licenses/index.json").writeString(mapper.writeValueAsString(licenseFiles), false);
} catch (IOException e) {
e.printStackTrace();
}
}Example 72
| Project: dropwizard-master File: RequestLogFactoryTest.java View source code |
@Before
public void setUp() throws Exception {
final ObjectMapper objectMapper = Jackson.newObjectMapper();
objectMapper.getSubtypeResolver().registerSubtypes(ConsoleAppenderFactory.class, FileAppenderFactory.class, SyslogAppenderFactory.class);
this.logbackAccessRequestLogFactory = new YamlConfigurationFactory<>(LogbackAccessRequestLogFactory.class, BaseValidator.newValidator(), objectMapper, "dw").build(new File(Resources.getResource("yaml/requestLog.yml").toURI()));
}Example 73
| Project: emitter-master File: ParametrizedUriEmitterFactory.java View source code |
@Override
public Emitter makeEmitter(ObjectMapper objectMapper, HttpClient httpClient, Lifecycle lifecycle) {
final String baseUri = getRecipientBaseUrlPattern();
final ParametrizedUriExtractor parametrizedUriExtractor = new ParametrizedUriExtractor(baseUri);
final Set<String> onlyFeedParam = new HashSet<>();
onlyFeedParam.add("feed");
UriExtractor uriExtractor = parametrizedUriExtractor;
if (parametrizedUriExtractor.getParams().equals(onlyFeedParam)) {
uriExtractor = new FeedUriExtractor(baseUri.replace("{feed}", "%s"));
}
final Emitter retVal = new ParametrizedUriEmitter(this, httpClient, objectMapper, uriExtractor);
lifecycle.addManagedInstance(retVal);
return retVal;
}Example 74
| Project: etcd-viewer-master File: EtcdSimulator.java View source code |
public void start() {
JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setResourceClasses(EtcdResource.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
sf.setProvider(new JacksonJsonProvider(mapper));
etcdResource = new EtcdResourceImpl();
sf.setResourceProvider(EtcdResource.class, new SingletonResourceProvider(etcdResource));
sf.setAddress("http://localhost:2379/");
endpointServer = sf.create();
endpointServer.start();
}Example 75
| Project: eve-java-master File: YamlReader.java View source code |
/**
* Load.
*
* @param is
* the is
* @return the config
*/
public static Config load(final InputStream is) {
final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
try {
return Config.decorate((ObjectNode) mapper.readTree(is));
} catch (final JsonProcessingException e) {
LOG.log(Level.WARNING, "Couldn't parse Yaml file", e);
} catch (final IOException e) {
LOG.log(Level.WARNING, "Couldn't read Yaml file", e);
}
return null;
}Example 76
| Project: fastjson-master File: Issue859.java View source code |
public void test_for_issue() throws Exception {
InputStream is = Issue72.class.getClassLoader().getResourceAsStream("issue859.zip");
GZIPInputStream gzipInputStream = new GZIPInputStream(is);
String text = org.apache.commons.io.IOUtils.toString(gzipInputStream);
long startMillis = System.currentTimeMillis();
for (int i = 0; i < 1; ++i) {
JSON.parseObject(text);
}
// new Gson().fromJson(text, java.util.HashMap.class);
//new ObjectMapper().readValue(text, java.util.HashMap.class);
long costMillis = System.currentTimeMillis() - startMillis;
System.out.println("cost : " + costMillis);
}Example 77
| Project: Fiazard-master File: MongoBundle.java View source code |
@Override
public void run(FiazardConfig configuration, Environment environment) throws Exception {
ManagedMongoClient mongoClient = configuration.getMongo().build();
db = mongoClient.getDB(configuration.getMongo().getDbName());
environment.lifecycle().manage(configuration.getMongo().build());
environment.healthChecks().register("MongoDBHealthCheck", new MongoDBHealthCheck(db));
eventStore = new EventStore(db);
objectMapper = MongoJackModule.configure(new ObjectMapper());
objectMapper.registerModule(MODULE);
}Example 78
| Project: Freshet-master File: InstanceCreatedEventFilter.java View source code |
@Override
public boolean isKeep(TridentTuple tuple) {
String eventData = tuple.getStringByField(Constants.FIELD_EVENT_DATA);
ObjectMapper objectMapper = new ObjectMapper();
try {
Map<String, Object> eventJson = objectMapper.readValue(eventData, Map.class);
if (eventJson.get("event-type") != null && ((String) eventJson.get("event-type")).equals("INSTANCE_CREATED")) {
return true;
}
} catch (IOException e) {
logger.error("Unable to parse event data JSON.", e);
}
return false;
}Example 79
| Project: fullcontact4j-master File: RequestModelTest.java View source code |
@Test
public void cardReaderBodyJsonSerializationTest() throws Exception {
ObjectMapper mapper = new ObjectMapper();
CardReaderUploadRequest.RequestBodyJson body = new CardReaderUploadRequest.RequestBodyJson();
body.setFront("test");
body.setBack("back test");
assertTrue(mapper.writeValueAsString(body).equals("{\"front\":\"test\",\"back\":\"back test\"}"));
}Example 80
| Project: GeoIP2-java-master File: AbstractRecord.java View source code |
/**
* @return JSON representation of this object. The structure is the same as
* the JSON provided by the GeoIP2 web service.
* @throws IOException if there is an error serializing the object to JSON.
*/
public String toJson() throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
mapper.configure(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS, false);
return mapper.writeValueAsString(this);
}Example 81
| Project: GreenBits-master File: WampCra.java View source code |
@Override
public WampMessages.AuthenticateMessage handleChallenge(WampMessages.ChallengeMessage message, ObjectMapper objectMapper) {
String challenge = message.extra.get("challenge").asText();
try {
String signature = calculateHmacSHA256(challenge, objectMapper);
return new WampMessages.AuthenticateMessage(signature, objectMapper.createObjectNode());
} catch (InvalidKeyException e) {
throw new RuntimeException("InvalidKeyException while calculating HMAC");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("NoSuchAlgorithmException while calculating HMAC");
}
}Example 82
| Project: griffon-master File: ObjectMapperProvider.java View source code |
@Override
@SuppressWarnings("unchecked")
public ObjectMapper get() {
final ObjectMapper om = new ObjectMapper();
ServiceLoaderUtils.load(getClass().getClassLoader(), "META-INF/services", JsonEntity.class, ( classLoader, type, line) -> {
try {
String className = line.trim();
Class<? extends JsonEntity> clazz = (Class<? extends JsonEntity>) classLoader.loadClass(className);
om.registerSubtypes(clazz);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(e);
}
});
return om;
}Example 83
| 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 84
| 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 85
| Project: ilves-master File: OAuthServiceTest.java View source code |
@Test
@Ignore
public void testGet() throws Exception {
final String response = OAuthService.get("https://api.github.com/user/emails", "xxx");
ObjectMapper objectMapper = new ObjectMapper();
final ArrayList<Map<String, Object>> emailList = (ArrayList<Map<String, Object>>) objectMapper.readValue(response, ArrayList.class);
System.out.println(emailList);
Assert.assertEquals(1, emailList.size());
Assert.assertEquals("tommi.s.e.laukkanen@gmail.com", emailList.get(0).get("email"));
Assert.assertTrue((Boolean) emailList.get(0).get("primary"));
Assert.assertTrue((Boolean) emailList.get(0).get("verified"));
}Example 86
| Project: IMM-master File: DefaultTypingTest.java View source code |
@Test
public void roundtrip() throws IOException {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enableDefaultTyping();
objectMapper.registerModule(new GuavaModule());
ImmutableOuterObject outer = ImmutableOuterObject.builder().emptyObject(ImmutableEmptyObject.builder().build()).build();
String serialized = objectMapper.writeValueAsString(outer);
check(objectMapper.readValue(serialized, ImmutableOuterObject.class)).is(outer);
}Example 87
| Project: immutables-master File: DefaultTypingTest.java View source code |
@Test
public void roundtrip() throws IOException {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enableDefaultTyping();
objectMapper.registerModule(new GuavaModule());
ImmutableOuterObject outer = ImmutableOuterObject.builder().emptyObject(ImmutableEmptyObject.builder().build()).build();
String serialized = objectMapper.writeValueAsString(outer);
check(objectMapper.readValue(serialized, ImmutableOuterObject.class)).is(outer);
}Example 88
| Project: intercom-java-master File: URIDeserializer.java View source code |
@Override
public URI deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
final ObjectMapper mapper = (ObjectMapper) jp.getCodec();
final ValueNode vNode = mapper.readTree(jp);
URI uri = null;
try {
uri = new URI(vNode.asText());
} catch (URISyntaxException ignored) {
}
if (uri == null) {
try {
final URL url = new URL(vNode.asText());
uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), url.getRef());
} catch (MalformedURLException ignored) {
} catch (URISyntaxException ignored) {
}
}
return uri;
}Example 89
| Project: jackson-dataformat-xml-master File: TestBinaryData.java View source code |
/*
/**********************************************************
/* Unit tests
/**********************************************************
*/
// private final XmlMapper MAPPER = new XmlMapper();
// for [https://github.com/FasterXML/jackson-dataformat-xml/issues/29]
public void testTwoBinaryProps() throws Exception {
/* Hmmh. Looks like XmlMapper has some issues with convertValue:
* should investigate at some point. But not now...
*/
final ObjectMapper jsonMapper = new ObjectMapper();
String BIN1 = jsonMapper.convertValue("Hello".getBytes("UTF-8"), String.class);
String BIN2 = jsonMapper.convertValue("world!!".getBytes("UTF-8"), String.class);
String xml = "<TwoData>" + "<data1><bytes>" + BIN1 + "</bytes></data1>" + "<data2><bytes>" + BIN2 + "</bytes></data2>" + "</TwoData>";
TwoData two = new XmlMapper().readValue(xml, TwoData.class);
assertEquals("Hello", new String(two.data1.bytes, "UTF-8"));
assertEquals("world!!", new String(two.data2.bytes, "UTF-8"));
}Example 90
| Project: jbpm-master File: JsonWorkItemParser.java View source code |
public static List<Map<String, Object>> parse(String json) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS, JsonTypeInfo.As.WRAPPER_ARRAY);
return mapper.readValue(json, ArrayList.class);
}Example 91
| Project: jira-version-generator-master File: ObjectMapperFactory.java View source code |
public static ObjectMapper getInstance() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new Jdk8Module()); objectMapper.registerModule(new ParameterNamesModule()); objectMapper.registerModule(new JavaTimeModule()); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); return objectMapper; }
Example 92
| Project: jongo-master File: AnnotationModifier.java View source code |
public void modify(ObjectMapper mapper) {
AnnotationIntrospector jongoIntrospector = new JongoAnnotationIntrospector();
AnnotationIntrospector defaultIntrospector = mapper.getSerializationConfig().getAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospectorPair(jongoIntrospector, defaultIntrospector);
mapper.setAnnotationIntrospector(pair);
}Example 93
| Project: joreman-master File: JSONHelper.java View source code |
public static <T> T load(Class<T> clz, String jsonFile) {
ContextResolver<ObjectMapper> ctx = ResteasyProviderFactory.getInstance().getContextResolver(ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE);
InputStream is = JSONHelper.class.getResourceAsStream(jsonFile);
try {
if (is != null) {
return ctx.getContext(null).readValue(is, clz);
} else {
File f = new File(jsonFile);
return ctx.getContext(null).readValue(f, clz);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 94
| Project: josm-geojson-master File: GeoJsonFileImporter.java View source code |
@Override
public void importData(File file, ProgressMonitor progressMonitor) {
GeoJsonObject object = null;
System.out.println("Parsing GeoJSON: " + file.getAbsolutePath());
try {
object = new ObjectMapper().readValue(file, GeoJsonObject.class);
System.out.println("Found: " + object.getClass());
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
GeoJsonLayer layer = new GeoJsonLayer("GeoJSON: " + file.getName(), object);
Main.main.addLayer(layer);
System.out.println("Added layer.");
}Example 95
| Project: jsondoc-master File: JSONDocTemplateBuilderWithOrderTest.java View source code |
@Test
public void thatTemplateIsMappedToStringCorrectly() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
Set<Class<?>> classes = Sets.<Class<?>>newHashSet(Unordered.class, Ordered.class);
Map<String, Object> unorderedTemplate = JSONDocTemplateBuilder.build(Unordered.class, classes);
Assert.assertEquals("{\"aField\":\"\",\"xField\":\"\"}", mapper.writeValueAsString(unorderedTemplate));
Map<String, Object> orderedTemplate = JSONDocTemplateBuilder.build(Ordered.class, classes);
Assert.assertEquals("{\"xField\":\"\",\"aField\":\"\",\"bField\":\"\"}", mapper.writeValueAsString(orderedTemplate));
}Example 96
| Project: jvm-serializers-master File: JacksonSmileDatabind.java View source code |
public static void register(TestGroups groups, boolean sharedNames, boolean sharedValues) {
SmileFactory factory = new SmileFactory();
factory.configure(SmileGenerator.Feature.CHECK_SHARED_NAMES, sharedNames);
factory.configure(SmileGenerator.Feature.CHECK_SHARED_STRING_VALUES, sharedValues);
// no point in using enum names with binary format, so:
ObjectMapper mapper = new ObjectMapper(factory);
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_INDEX);
groups.media.add(JavaBuiltIn.mediaTransformer, new StdJacksonDataBind<MediaContent>("smile/jackson/databind", MediaContent.class, mapper), new SerFeatures(SerFormat.BINARY, SerGraph.FLAT_TREE, SerClass.ZERO_KNOWLEDGE, ""));
}Example 97
| Project: kaif-master File: FlakeIdTest.java View source code |
@Test
public void json() throws Exception {
ObjectMapper mapper = new ObjectMapper();
assertEquals("\"gVKJo\"", mapper.writeValueAsString(FlakeId.valueOf(100000000L)));
assertEquals(FlakeId.fromString("foo"), mapper.readValue("\"foo\"", FlakeId.class));
assertEquals("{\"flakeId\":\"vZF7Nk\"}", mapper.writeValueAsString(new FooPojo(FlakeId.valueOf(20000000000L))));
assertEquals(FlakeId.fromString("xyz"), mapper.readValue("{\"flakeId\":\"xyz\"}", FooPojo.class).flakeId);
}Example 98
| Project: katharsis-core-master File: BaseSerializerTest.java View source code |
@Before
public void setUp() throws Exception {
ResourceInformationBuilder resourceInformationBuilder = new ResourceInformationBuilder(new ResourceFieldNameTransformer());
ResourceRegistryBuilder registryBuilder = new ResourceRegistryBuilder(new SampleJsonServiceLocator(), resourceInformationBuilder);
resourceRegistry = registryBuilder.build(ResourceRegistryBuilderTest.TEST_MODELS_PACKAGE, ResourceRegistryTest.TEST_MODELS_URL);
JsonApiModuleBuilder jsonApiModuleBuilder = new JsonApiModuleBuilder();
sut = new ObjectMapper();
sut.registerModule(jsonApiModuleBuilder.build(resourceRegistry));
JsonPath jsonPath = new PathBuilder(resourceRegistry).buildPath("/tasks");
testResponse = new ResourceResponseContext(buildResponse(null), jsonPath, new QueryParams());
}Example 99
| 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 100
| Project: lab-master File: TestUtil.java View source code |
public static byte[] convertObjectToFormUrlEncodedBytes(Object object) {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
@SuppressWarnings("unchecked") Map<String, Object> propertyValues = mapper.convertValue(object, Map.class);
Set<String> propertyNames = propertyValues.keySet();
Iterator<String> nameIter = propertyNames.iterator();
StringBuilder formUrlEncoded = new StringBuilder();
for (int index = 0; index < propertyNames.size(); index++) {
String currentKey = nameIter.next();
Object currentValue = propertyValues.get(currentKey);
formUrlEncoded.append(currentKey);
formUrlEncoded.append("=");
formUrlEncoded.append(currentValue);
if (nameIter.hasNext()) {
formUrlEncoded.append("&");
}
}
return formUrlEncoded.toString().getBytes();
}Example 101
| Project: launchkey-java-master File: ServiceV3AuthsPostRequestPolicyTest.java View source code |
@Test
public void objectMapperMapsAsExpected() throws Exception {
String expected = "{" + "\"minimum_requirements\":[{" + "\"requirement\":\"authenticated\"," + "\"any\":2," + "\"knowledge\":1," + "\"inherence\":1," + "\"possession\":1" + "}]," + "\"factors\":[" + "{" + "\"factor\":\"geofence\"," + "\"requirement\":\"forced requirement\"," + "\"priority\":1," + "\"attributes\":{" + "\"locations\":[" + "{\"radius\":1.1,\"latitude\":2.1,\"longitude\":3.1}," + "{\"radius\":1.2,\"latitude\":2.2,\"longitude\":3.2}" + "]" + "}" + "}" + "]" + "}";
ServiceV3AuthsPostRequestPolicy policy = new ServiceV3AuthsPostRequestPolicy(2, true, true, true);
policy.addGeoFence(1.1, 2.1, 3.1);
policy.addGeoFence(1.2, 2.2, 3.2);
String actual = new ObjectMapper().writeValueAsString(policy);
assertEquals(expected, actual);
}