/** * Return the Jackson {@link JavaType} for the specified type and context class. * * <p>The default implementation returns {@code typeFactory.constructType(type, contextClass)}, * but this can be overridden in subclasses, to allow for custom generic collection handling. For * instance: * * <pre class="code"> * protected JavaType getJavaType(Type type) { * if (type instanceof Class && List.class.isAssignableFrom((Class)type)) { * return TypeFactory.collectionType(ArrayList.class, MyBean.class); * } else { * return super.getJavaType(type); * } * } * </pre> * * @param type the generic type to return the Jackson JavaType for * @param contextClass a context class for the target type, for example a class in which the * target type appears in a method signature (can be {@code null}) * @return the Jackson JavaType */ protected JavaType getJavaType(Type type, Class<?> contextClass) { TypeFactory typeFactory = this.objectMapper.getTypeFactory(); if (type instanceof TypeVariable && contextClass != null) { ResolvableType resolvedType = resolveVariable((TypeVariable<?>) type, ResolvableType.forClass(contextClass)); if (resolvedType != ResolvableType.NONE) { return typeFactory.constructType(resolvedType.resolve()); } } return typeFactory.constructType(type); }
/** * Method called by {@link BeanDeserializerFactory} to see if there might be a standard * deserializer registered for given type. */ @SuppressWarnings("unchecked") protected JsonDeserializer<Object> findStdDeserializer( DeserializationConfig config, JavaType type) throws JsonMappingException { Class<?> cls = type.getRawClass(); // note: we do NOT check for custom deserializers here; that's for sub-class to do JsonDeserializer<Object> deser = _simpleDeserializers.get(new ClassKey(cls)); if (deser != null) { return deser; } // [JACKSON-283]: AtomicReference is a rather special type... if (AtomicReference.class.isAssignableFrom(cls)) { // Must find parameterization TypeFactory tf = config.getTypeFactory(); JavaType[] params = tf.findTypeParameters(type, AtomicReference.class); JavaType referencedType; if (params == null || params.length < 1) { // untyped (raw) referencedType = TypeFactory.unknownType(); } else { referencedType = params[0]; } JsonDeserializer<?> d2 = new JdkDeserializers.AtomicReferenceDeserializer(referencedType); return (JsonDeserializer<Object>) d2; } // [JACKSON-386]: External/optional type handlers are handled somewhat differently JsonDeserializer<?> d = optionalHandlers.findDeserializer(type, config); if (d != null) { return (JsonDeserializer<Object>) d; } return null; }
private Flux<Object> decodeInternal( JsonObjectDecoder objectDecoder, Publisher<DataBuffer> inputStream, ResolvableType elementType, MimeType mimeType, Object[] hints) { Assert.notNull(inputStream, "'inputStream' must not be null"); Assert.notNull(elementType, "'elementType' must not be null"); TypeFactory typeFactory = this.mapper.getTypeFactory(); JavaType javaType = typeFactory.constructType(elementType.getType()); ObjectReader reader = this.mapper.readerFor(javaType); return objectDecoder .decode(inputStream, elementType, mimeType, hints) .map( dataBuffer -> { try { Object value = reader.readValue(dataBuffer.asInputStream()); DataBufferUtils.release(dataBuffer); return value; } catch (IOException e) { return Flux.error(new CodecException("Error while reading the data", e)); } }); }
protected <T> Object[] parseIn(Expression<?> path, JsonNode fieldValue) throws QueryInfoException { Class<?> javaType = path.getJavaType(); TypeFactory typeFactory = objectMapper.getTypeFactory(); ArrayType arrayType = typeFactory.constructArrayType(javaType); return objectMapper.convertValue(fieldValue, arrayType); }
private void getSheetContent(String jsonString, HSSFSheet sheet) { try { MapType mt = TypeFactory.defaultInstance().constructMapType(HashMap.class, String.class, String.class); CollectionType ct = TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, mt); List<Map<String, String>> prms = JsonParser.json2Object(ct, jsonString); for (int i = 0; i < prms.size(); i++) { HSSFRow rowi = sheet.createRow(i); Set<Entry<String, String>> set = prms.get(i).entrySet(); for (Entry<String, String> en : set) { if (!"id".equals(en.getKey()) && !"displayOrder".equals(en.getKey())) { if (en.getValue() != null) { String value = en.getValue(); if ("name".equals(en.getKey())) { HSSFCell celli0 = rowi.createCell(0); celli0.setCellValue(value); continue; } if ("dbColumnName".equals(en.getKey())) { HSSFCell celli1 = rowi.createCell(1); celli1.setCellValue(value); continue; } if ("alias".equals(en.getKey())) { HSSFCell celli2 = rowi.createCell(2); celli2.setCellValue(value); continue; } if ("dataType".equals(en.getKey())) { HSSFCell celli3 = rowi.createCell(3); celli3.setCellValue(value); continue; } if ("defaultValue".equals(en.getKey())) { HSSFCell celli4 = rowi.createCell(4); celli4.setCellValue(value); continue; } if ("maxLength".equals(en.getKey())) { HSSFCell celli5 = rowi.createCell(5); celli5.setCellValue(value); continue; } } } } HSSFCell celli6 = rowi.createCell(6); celli6.setCellValue(i); } } catch (Exception e) { } }
public static JsonHeader deserializeJsonHeader(final String ratJson) throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); RATJsonObject ratJsonObject = (RATJsonObject) mapper.readValue(ratJson, RATJsonObject.class); TypeFactory typeFactory = mapper.getTypeFactory(); MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, String.class); HashMap<String, String> map = mapper.readValue(ratJsonObject.getHeader(), mapType); JsonHeader header = new JsonHeader(); header.setHeaderProperties(map); return header; }
public <T> T copy(T input) throws ObjectCopyException { try { byte[] bytes = mapper.writeValueAsBytes(input); TypeFactory tf = mapper.getTypeFactory(); JavaType type = tf.constructType(input.getClass()); return mapper.readValue(bytes, type); } catch (IOException e) { log.error("error in copying input", e); throw new ObjectCopyException("error in copying input", e); } }
/** * Invokes the given method on the {@code handler} passing the given params (after converting them * to beans\objects) to it. * * @param m the method to invoke * @param params the params to pass to the method * @return the return value (or null if no return) * @throws IOException on error * @throws IllegalAccessException on error * @throws InvocationTargetException on error */ protected JsonNode invoke(Method m, List<JsonNode> params) throws IOException, IllegalAccessException, InvocationTargetException { // debug log if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Invoking method: " + m.getName()); } // convert the parameters Object[] convertedParams = new Object[params.size()]; Type[] parameterTypes = m.getGenericParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { JsonParser paramJsonParser = mapper.treeAsTokens(params.get(i)); JavaType paramJavaType = TypeFactory.defaultInstance().constructType(parameterTypes[i]); convertedParams[i] = mapper.readValue(paramJsonParser, paramJavaType); } // invoke the method Object result = m.invoke(handler, convertedParams); Type genericReturnType = m.getGenericReturnType(); if (genericReturnType != null) { if (Collection.class.isInstance(result) && genericReturnType instanceof ParameterizedType) { try { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "attempting custom collection serialization"); } TypeFactory typeFactory = mapper.getTypeFactory(); Type actualTypeInCollection = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; if (actualTypeInCollection instanceof TypeVariable) { // collection actually has a generic return type actualTypeInCollection = ((TypeVariable) actualTypeInCollection).getBounds()[0]; } JavaType rootType = typeFactory.constructCollectionType( Collection.class, typeFactory.constructType(actualTypeInCollection)); return valueToTree(mapper.writerWithType(rootType), result); } catch (Exception e) { LOGGER.log( Level.WARNING, "could not do custom collection serialization falling back to default", e); } } return mapper.valueToTree(result); } else { return null; } // return (genericReturnType!=null) ? mapper.valueToTree(result) : null; }
/** * Parse Json File and create list of {@link WidgetGroup}. * * @param path */ public void read(String path) { ObjectMapper mapper = new ObjectMapper(); try { // JSON from file to Object TypeFactory typeFactory = TypeFactory.defaultInstance(); String json = TextFileUtils.readFileFromJar(path); widgetGroupList = mapper.readValue( json, typeFactory.constructCollectionType(ArrayList.class, DefaultWidgetGroup.class)); } catch (IOException ex) { Logger.getLogger(JsonReader.class.getName()).log(Level.SEVERE, null, ex); } }
@Override public void process(Exchange exchange) throws Exception { String message = exchange.getIn().getBody(String.class); ObjectMapper objectMapper = new ObjectMapper(); TypeFactory typeFactory = objectMapper.getTypeFactory(); List<Double> values = objectMapper.readValue( message, typeFactory.constructCollectionType(List.class, Double.class)); SummaryStatistics summaryStatistics = new SummaryStatistics(); List<Double> list = new ObjectMapper().readValue(message, List.class); for (Double value : list) { summaryStatistics.addValue(value); } String variance = Double.toString(summaryStatistics.getVariance()); exchange.getOut().setBody(variance); }
public <T> List<T> readValueAsObjectList(String h, Class clazz) { List<T> list = null; try { TypeFactory t = TypeFactory.defaultInstance(); list = Utils.instance .getObjectMapper() .readValue(h, t.constructCollectionType(ArrayList.class, clazz)); return list; } catch (JsonProcessingException e) { e.printStackTrace(); return list; } catch (IOException e) { e.printStackTrace(); return list; } }
public ListenableFuture<Map<JobId, JobStatus>> jobStatuses(final Set<JobId> jobs) { final ConvertResponseToPojo<Map<JobId, JobStatus>> converter = ConvertResponseToPojo.create( TypeFactory.defaultInstance().constructMapType(Map.class, JobId.class, JobStatus.class), ImmutableSet.of(HTTP_OK)); return transform(request(uri("/jobs/statuses"), "POST", jobs), converter); }
/** * Add the route in the database if it's not already, or update its state. * * @param routes being added to the app */ @Override public void onRoutesAdd(Collection<Route> routes) { for (Route routeCamel : routes) { // adding a performance counter on the route if (routeCamel instanceof EventDrivenConsumerRoute) { EventDrivenConsumerRoute edcr = (EventDrivenConsumerRoute) routeCamel; Processor processor = edcr.getProcessor(); if (processor instanceof InstrumentationProcessor) { InstrumentationProcessor ip = (InstrumentationProcessor) processor; ConsolePerformanceCounter counter = new ConsolePerformanceCounter(routeCamel.getId(), repository); ip.setCounter(counter); log.debug("Adding a counter" + counter.toString() + " to " + routeCamel.getId()); } } // saving route in database log.debug("Route added " + routeCamel.getId()); com.ninja_squad.console.Route route = repository.findRoute(routeCamel.getId()); if (route == null) { route = new com.ninja_squad.console.Route(routeCamel.getId()) .state(State.Started) .uri(routeCamel.getEndpoint().getEndpointUri()); ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); // make serializer use JAXB annotations (only) mapper.setAnnotationIntrospector(introspector); String definition = null; RouteDefinition routeDefinition = routeCamel.getRouteContext().getRoute(); try { definition = mapper.writeValueAsString(routeDefinition); } catch (IOException e) { log.error("Error while marshalling route definition", e); } route.setDefinition(definition); for (ProcessorDefinition<?> stepDefinition : routeDefinition.getOutputs()) { if (stepDefinition.getId() == null) { stepDefinition.setId(stepDefinition.getClass().getSimpleName()); } route.getSteps().put(stepDefinition.getId(), stepDefinition.getLabel()); } repository.save(route); } // saving state in database RouteState routeState = repository.lastRouteState(routeCamel.getId()); if (routeState == null || routeState.getState().equals(State.Stopped)) { routeState = new RouteState(); routeState.setRouteId(routeCamel.getId()); routeState.setState(State.Started); routeState.setTimestamp(DateTime.now().getMillis()); repository.save(routeState); } } }
/** * 把JSON转成list中是MAP《String,clazz》 * * @param json * @param clazz * @return */ @SuppressWarnings({"rawtypes"}) public Object getJsonToListByMap(String json, Class clazz) { Object object = null; if (StringUtils.isNotBlank(json)) { try { object = getMapper() .readValue( json, TypeFactory.defaultInstance() .constructArrayType( TypeFactory.defaultInstance() .constructMapType(HashMap.class, String.class, clazz))); } catch (Exception e) { e.printStackTrace(); } } return object; }
public ListenableFuture<Map<String, HostStatus>> hostStatuses( final List<String> hosts, final Map<String, String> queryParams) { final ConvertResponseToPojo<Map<String, HostStatus>> converter = ConvertResponseToPojo.create( TypeFactory.defaultInstance() .constructMapType(Map.class, String.class, HostStatus.class), ImmutableSet.of(HTTP_OK)); return transform(request(uri("/hosts/statuses", queryParams), "POST", hosts), converter); }
private List<Session> restoreSessions(File file) { try { return mapper.readValue(file, factory.constructCollectionType(List.class, Session.class)); } catch (JsonMappingException jme) { logger.error("exception found", jme); return newArrayList(); } catch (IOException e) { throw new RuntimeException(e); } }
public static XmlMapper newXmlMapper() { XmlMapper xmlMapper = new XmlMapper(); final AnnotationIntrospector primary = new JacksonAnnotationIntrospector(); final AnnotationIntrospector secondary = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); final AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary); xmlMapper.setAnnotationIntrospector(pair); xmlMapper.registerModule(new JodaModule()); xmlMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); return xmlMapper; }
/** * 把JSON转成Map<> value是LIST类型 * * @param json * @param keyclazz * @param valueclazz LIST中的CLASS * @return */ @SuppressWarnings("rawtypes") public Object getJsonToMapByList(String json, Class keyclazz, Class valueclazz) { Object object = null; if (StringUtils.isNotBlank(json)) { try { object = getMapper() .readValue( json, TypeFactory.defaultInstance() .constructMapType( HashMap.class, TypeFactory.defaultInstance().uncheckedSimpleType(keyclazz), TypeFactory.defaultInstance() .constructCollectionType(ArrayList.class, valueclazz))); } catch (Exception e) { e.printStackTrace(); } } return object; }
/** * Additional simple tests to ensure we will retain basic namespace information now that it can be * included * * @since 2.1 */ public void testNamespaces() throws Exception { JaxbAnnotationIntrospector ai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); AnnotatedClass ac = AnnotatedClass.construct(NamespaceBean.class, ai, null); AnnotatedField af = _findField(ac, "string"); assertNotNull(af); PropertyName pn = ai.findNameForDeserialization(af); assertNotNull(pn); // JAXB seems to assert field name instead of giving "use default"... assertEquals("", pn.getSimpleName()); assertEquals("urn:method", pn.getNamespace()); }
@Test public void testTickerAdapter() throws IOException { // Read in the JSON from the example resources InputStream is = Btc38AdapterTest.class.getResourceAsStream("/example-ticker-data.json"); // Use Jackson to parse it ObjectMapper mapper = new ObjectMapper(); TypeFactory t = TypeFactory.defaultInstance(); Map<String, Btc38TickerReturn> btc38AllTickers = mapper.readValue(is, t.constructMapType(Map.class, String.class, Btc38TickerReturn.class)); Btc38TickerReturn tickerReturn = btc38AllTickers.get("doge"); Ticker ticker = Btc38Adapters.adaptTicker(tickerReturn.getTicker(), CurrencyPair.DOGE_BTC); assertThat(ticker.getHigh()).isEqualTo(new BigDecimal("6.0e-7")); assertThat(ticker.getLow()).isEqualTo(new BigDecimal("5.1e-7")); assertThat(ticker.getLast()).isEqualTo(new BigDecimal("5.5e-7")); assertThat(ticker.getVolume()).isEqualTo(new BigDecimal("9201658.258436")); assertThat(ticker.getAsk()).isEqualTo(new BigDecimal("5.7e-7")); assertThat(ticker.getBid()).isEqualTo(new BigDecimal("5.5e-7")); }
@Override public Object fromBody(TypedInput body, final Type type) throws ConversionException { try { final JavaType javaType = TypeFactory.defaultInstance().constructType(type); return objectMapper.readValue(body.in(), javaType); } catch (final JsonParseException e) { throw new ConversionException(e); } catch (final JsonMappingException e) { throw new ConversionException(e); } catch (final IOException e) { throw new ConversionException(e); } }
public byte[] getJsonTobyteArray(String json) { byte[] object = null; if (StringUtils.isNotBlank(json)) { try { object = getMapper() .readValue(json, TypeFactory.defaultInstance().constructArrayType(byte.class)); } catch (Exception e) { e.printStackTrace(); } } return object; }
private static ObjectMapper createMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); mapper.setDateFormat(dateFormat); mapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance())); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); mapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true); addQueryMapper(mapper); return mapper; }
/** * 把JSON转成Object * * @param json * @param keyclazz * @param valueclazz * @return */ @SuppressWarnings({"rawtypes"}) public Object getJsonToObject(String json, Class objclazz, Class... pclazz) { Object object = null; if (StringUtils.isNotBlank(json)) { try { object = getMapper() .readValue( json, TypeFactory.defaultInstance().constructParametricType(objclazz, pclazz)); } catch (Exception e) { } } return object; }
public void testSimpleKeySer() throws Exception { ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule("test", Version.unknownVersion()); module.addKeySerializer(String.class, new ContextualKeySerializer("prefix")); mapper.registerModule(module); Map<String, Object> input = new HashMap<String, Object>(); input.put("a", Integer.valueOf(3)); String json = mapper .writerWithType( TypeFactory.defaultInstance() .constructMapType(HashMap.class, String.class, Object.class)) .writeValueAsString(input); assertEquals("{\"prefix:a\":3}", json); }
public void testRootNameAccess() throws Exception { AnnotationIntrospector ai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); // If no @XmlRootElement, should get null (unless pkg has etc) assertNull(ai.findRootName(AnnotatedClass.construct(SimpleBean.class, ai, null))); // With @XmlRootElement, but no name, empty String PropertyName rootName = ai.findRootName(AnnotatedClass.construct(NamespaceBean.class, ai, null)); assertNotNull(rootName); assertEquals("", rootName.getSimpleName()); assertEquals("urn:class", rootName.getNamespace()); // and otherwise explicit name rootName = ai.findRootName(AnnotatedClass.construct(RootNameBean.class, ai, null)); assertNotNull(rootName); assertEquals("test", rootName.getSimpleName()); assertNull(rootName.getNamespace()); }
/** * 把JSON转成并发Map * * @param json * @param keyclazz * @param valueclazz * @return */ @SuppressWarnings({"rawtypes"}) public Object getJsonToConcMap(String json, Class keyclazz, Class valueclazz) { Object object = null; if (StringUtils.isNotBlank(json)) { try { object = getMapper() .readValue( json, TypeFactory.defaultInstance() .constructParametricType(ConcurrentHashMap.class, keyclazz, valueclazz)); } catch (Exception e) { e.printStackTrace(); } } return object; }
/** * Method that can be used to find out actual output (target) type; this usually can be determined * from type parameters, but may need to be implemented differently from programmatically defined * converters (which can not change static type parameter bindings). * * @param typeFactory * @since 2.2 */ @Override public JavaType getOutputType(TypeFactory typeFactory) { return typeFactory.constructType(ResponseCode.class); }
/** * Method that can be used to find out actual input (source) type; this usually can be determined * from type parameters, but may need to be implemented differently from programmatically defined * converters (which can not change static type parameter bindings). * * @param typeFactory * @since 2.2 */ @Override public JavaType getInputType(TypeFactory typeFactory) { return typeFactory.constructType(Integer.class); }
@SuppressWarnings("rawtypes") public static JavaType buildCollectionType( final Class<? extends Collection> collection, final Class<?> element) { return typeFactory.constructCollectionType(collection, element); }