List of usage examples for com.fasterxml.jackson.databind ObjectMapper convertValue
@SuppressWarnings("unchecked") public <T> T convertValue(Object fromValue, JavaType toValueType) throws IllegalArgumentException
From source file:com.microsoft.office365.meetingmgr.HttpHelper.java
private <TResult> PagedResult<TResult> doGetItems(String uri, int itemCount, int pageCount, Class<TResult> clazz) { String fullUri = buildUri(uri); List<TResult> result = new ArrayList<>(); ObjectMapper mapper = new JsonMapper(); while (pageCount-- > 0 && itemCount > 0 && fullUri != null) { ODataListBase<TResult> list = createList(fullUri); list = getItem(fullUri, list.getClass()); if (list == null) { return new PagedResult<>(null, null); }//ww w . j ava 2 s . c o m fullUri = list.getNextLink(fullUri); for (Object el : list.value) { --itemCount; result.add(mapper.convertValue(el, clazz)); } } return new PagedResult<>(result, fullUri); }
From source file:org.openlmis.fulfillment.web.BaseWebIntegrationTest.java
<T> List<T> getPageContent(Page page, Class<T> type) { List content = page.getContent(); if (isEmpty(content)) { // nothing to do return Collections.emptyList(); }//from w w w. j a v a 2s .c o m if (type.isInstance(content.get(0))) { // content contains instances of the given type return Collections.checkedList(content, type); } if (content.get(0) instanceof Map) { // jackson does not convert json to correct type // instead it use default operation and objects are // represented by Map // We have to do manually convert map to the given type =( ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); TypeFactory factory = mapper.getTypeFactory(); CollectionLikeType collectionType = factory.constructCollectionLikeType(List.class, type); return mapper.convertValue(content, collectionType); } throw new IllegalStateException("the page content contains unsupported type"); }
From source file:org.springframework.boot.actuate.endpoint.ConfigurationPropertiesReportEndpoint.java
/** * Cautiously serialize the bean to a map (returning a map with an error message * instead of throwing an exception if there is a problem). *//*from w w w. ja v a 2 s.c om*/ private Map<String, Object> safeSerialize(ObjectMapper mapper, Object bean, String prefix) { if (this.metadata == null) { this.metadata = new ConfigurationPropertiesMetaData(this.metadataLocations); } try { @SuppressWarnings("unchecked") Map<String, Object> result = new HashMap<String, Object>( mapper.convertValue(this.metadata.extractMap(bean, prefix), Map.class)); return result; } catch (Exception ex) { return new HashMap<String, Object>( Collections.<String, Object>singletonMap("error", "Cannot serialize '" + prefix + "'")); } }
From source file:com.couchbase.lite.DocumentTest.java
/** * Assert that if you add a/*from w w w . j a v a2 s . c om*/ * * @throws Exception */ public void testNonPrimitiveTypesInDocument() throws Exception { Object fooProperty; Map<String, Object> props = new HashMap<String, Object>(); Foo foo = new Foo(); foo.setBar("basic"); props.put("foo", foo); Document doc = createDocumentWithProperties(database, props); fooProperty = doc.getProperties().get("foo"); assertTrue(fooProperty instanceof Map); assertFalse(fooProperty instanceof Foo); Document fetched = database.getDocument(doc.getId()); fooProperty = fetched.getProperties().get("foo"); assertTrue(fooProperty instanceof Map); assertFalse(fooProperty instanceof Foo); ObjectMapper mapper = new ObjectMapper(); Foo fooResult = mapper.convertValue(fooProperty, Foo.class); assertEquals(foo.bar, fooResult.bar); }
From source file:eu.europa.ec.fisheries.uvms.spatial.service.bean.impl.AreaServiceBean.java
@Override public Map<String, Object> getClosestPointByPoint(@NotNull Double longitude, @NotNull Double latitude, @NotNull Integer crs) throws ServiceException { Point point = (Point) GeometryUtils.toGeographic(latitude, longitude, crs); GeodeticCalculator calc = new GeodeticCalculator(GeometryUtils.toDefaultCoordinateReferenceSystem()); List<PortEntity> records = repository.listClosestPorts(point, 5); Double closestDistance = Double.MAX_VALUE; PortEntity match = null;//www . j a v a 2s . c om for (PortEntity portsEntity : records) { Geometry geometry = portsEntity.getGeom(); Point centroid = geometry.getCentroid(); calc.setStartingGeographicPoint(centroid.getX(), centroid.getY()); calc.setDestinationGeographicPoint(point.getX(), point.getY()); Double orthodromicDistance = calc.getOrthodromicDistance(); if (closestDistance > orthodromicDistance) { closestDistance = orthodromicDistance; match = portsEntity; } } ObjectMapper objectMapper = new ObjectMapper(); Map map = objectMapper.convertValue(match, Map.class); return map; }
From source file:com.yahoo.elide.parsers.state.CollectionTerminalState.java
@Override public Supplier<Pair<Integer, JsonNode>> handleGet(StateContext state) { JsonApiDocument jsonApiDocument = new JsonApiDocument(); RequestScope requestScope = state.getRequestScope(); ObjectMapper mapper = requestScope.getMapper().getObjectMapper(); Optional<MultivaluedMap<String, String>> queryParams = requestScope.getQueryParams(); Set<PersistentResource> collection = getResourceCollection(requestScope); // Set data//from ww w . j av a 2 s . co m jsonApiDocument.setData(getData(requestScope, collection)); // Run include processor DocumentProcessor includedProcessor = new IncludedProcessor(); includedProcessor.execute(jsonApiDocument, collection, queryParams); DocumentProcessor sortProcessor = new SortProcessor(); sortProcessor.execute(jsonApiDocument, collection, queryParams); JsonNode responseBody = mapper.convertValue(jsonApiDocument, JsonNode.class); return () -> Pair.of(HttpStatus.SC_OK, responseBody); }
From source file:de.muenchen.eaidemo.AbstractIntegrationTest.java
/** * @param requestMappingUrl should be exactly the same as defined in your * RequestMapping value attribute (including the parameters in {}) * RequestMapping(value = yourRestUrl)/*w w w . j av a 2 s .c o m*/ * @param serviceListReturnTypeClass should be the the generic type of the * list the service returns, eg: List<serviceListReturnTypeClass> * @param parametersInOrderOfAppearance should be the parameters of the * requestMappingUrl ({}) in order of appearance * @return the result of the service, or null on error */ protected <T> List<T> getList(final String requestMappingUrl, final Class<T> serviceListReturnTypeClass, final Object... parametersInOrderOfAppearance) { final ObjectMapper mapper = new ObjectMapper(); final TestRestTemplate restTemplate = new TestRestTemplate(); final HttpEntity<String> requestEntity = new HttpEntity<String>(new HttpHeaders()); try { // Retrieve list final ResponseEntity<List> entity = restTemplate.exchange(getBaseUrl() + requestMappingUrl, HttpMethod.GET, requestEntity, List.class, parametersInOrderOfAppearance); final List<Map<String, String>> entries = entity.getBody(); final List<T> returnList = new ArrayList<T>(); for (final Map<String, String> entry : entries) { // Fill return list with converted objects returnList.add(mapper.convertValue(entry, serviceListReturnTypeClass)); } return returnList; } catch (final Exception ex) { // Handle exceptions } return null; }
From source file:eu.europa.ec.fisheries.uvms.spatial.service.bean.impl.AreaServiceBean.java
@Override public Map<String, Object> getLocationDetails(final LocationTypeEntry locationTypeEntry) throws ServiceException { BaseAreaEntity match = null;//from w w w . j av a 2 s. co m GeodeticCalculator calc = new GeodeticCalculator(GeometryUtils.toDefaultCoordinateReferenceSystem()); String id = locationTypeEntry.getId(); String locationType = locationTypeEntry.getLocationType(); AreaLocationTypesEntity locationTypesEntity; Double incomingLatitude = locationTypeEntry.getLatitude(); Double incomingLongitude = locationTypeEntry.getLongitude(); if (id != null && !StringUtils.isNumeric(id)) { throw new SpatialServiceException(SpatialServiceErrors.INVALID_ID_TYPE, id); } locationTypesEntity = repository.findAreaLocationTypeByTypeName(locationType.toUpperCase()); if (locationTypesEntity == null) { throw new ServiceException("TYPE CANNOT BE NULL"); } else if (!locationTypesEntity.getIsLocation()) { throw new ServiceException(locationTypesEntity.getTypeName() + " IS NOT A LOCATION"); } if (locationTypeEntry.getId() != null) { AbstractAreaDao dao = DAOFactory.getAbstractSpatialDao(em, locationTypesEntity.getTypeName()); BaseAreaEntity areaEntity = dao.findOne(Long.parseLong(locationTypeEntry.getId())); if (areaEntity == null) { throw new SpatialServiceException(SpatialServiceErrors.ENTITY_NOT_FOUND, locationTypesEntity.getTypeName()); } match = areaEntity; } else { Point point = (Point) GeometryUtils.toGeographic(incomingLatitude, incomingLongitude, locationTypeEntry.getCrs()); List<PortEntity> records = repository.listClosestPorts(point, 5); Double closestDistance = Double.MAX_VALUE; for (PortEntity portsEntity : records) { final Geometry geometry = portsEntity.getGeom(); final Point centroid = geometry.getCentroid(); calc.setStartingGeographicPoint(centroid.getX(), centroid.getY()); calc.setDestinationGeographicPoint(point.getX(), point.getY()); Double orthodromicDistance = calc.getOrthodromicDistance(); if (closestDistance > orthodromicDistance) { closestDistance = orthodromicDistance; match = portsEntity; } } } ObjectMapper objectMapper = new ObjectMapper(); Map map = objectMapper.convertValue(match, Map.class); return map; }
From source file:eu.europa.ec.fisheries.uvms.spatial.service.bean.impl.AreaServiceBean.java
@Override @Interceptors(ValidationInterceptor.class) public Map<String, Object> getAreaById(@NotNull Long id, @NotNull AreaType areaType) throws ServiceException { BaseAreaEntity area = repository.findAreaById(id, areaType); if (area == null) { throw new SpatialServiceException(SpatialServiceErrors.ENTITY_NOT_FOUND, areaType.value()); }/*from w w w . j a v a2s. co m*/ ObjectMapper objectMapper = new ObjectMapper(); @SuppressWarnings("unchecked") Map<String, Object> map = objectMapper.convertValue(area, Map.class); return map; }
From source file:org.apache.streams.facebook.serializer.FacebookActivityUtil.java
/** * Fills out the extensions attribute of the passed in {@link org.apache.streams.pojo.json.Activity} * @param activity//from ww w . jav a 2 s . c o m * @param post */ public static void buildExtensions(Activity activity, Post post) { ObjectMapper mapper = StreamsJacksonMapper.getInstance(); Map<String, Object> extensions = ExtensionUtil.ensureExtensions(activity); if (post.getLikes() != null && post.getLikes().size() > 0) { Map<String, Object> likes = Maps.newHashMap(); org.apache.streams.facebook.Like like = post.getLikes().get(0); if (like.getAdditionalProperties().containsKey("data")) { extensions.put("likes", likes); } } if (post.getShares() != null) { Map<String, Object> shares = Maps.newHashMap(); shares.put("count", ((Map<String, Object>) post.getShares()).get("count")); extensions.put("rebroadcasts", shares); } if (post.getTo() != null) { To to = post.getTo(); List<Datum> data = to.getData(); extensions.put("user_mentions", Lists.newArrayList()); for (Datum d : data) { Map<String, String> mention = Maps.newHashMap(); mention.put("id", d.getId()); mention.put("displayName", d.getName()); mention.put("handle", d.getName()); ((List<Map<String, String>>) extensions.get("user_mentions")).add(mention); } } if (post.getPlace() != null) { Place place = post.getPlace(); if (place.getAdditionalProperties().containsKey("location")) { extensions.put(LOCATION_EXTENSION, place.getAdditionalProperties().get("location")); } } extensions.put("facebook", mapper.convertValue(post, ObjectNode.class)); }