@SneakyThrows private void updateTenants(String key, String config) { log.info("Tenants list was updated"); if (!TENANTS_LIST_CONFIG_KEY.equals(key)) { throw new IllegalArgumentException("Wrong config key to update " + key); } assertExistsTenantsListConfig(config); CollectionType setType = defaultInstance().constructCollectionType(HashSet.class, TenantState.class); MapType type = defaultInstance().constructMapType(HashMap.class, defaultInstance().constructType(String.class), setType); Map<String, Set<TenantState>> tenantsByServiceMap = objectMapper.readValue(config, type); Set<TenantState> tenantKeys = tenantsByServiceMap.get(applicationName); assertExistTenants(tenantKeys); this.tenants = tenantKeys; this.suspendedTenants = tenantKeys.stream().filter(tenant -> SUSPENDED_STATE.equals(tenant.getState())) .map(TenantState::getName).collect(Collectors.toSet()); }
@SneakyThrows private void updateTenants(String config) { log.info("Tenants list was updated"); CollectionType setType = defaultInstance().constructCollectionType(HashSet.class, TenantState.class); MapType type = defaultInstance().constructMapType(HashMap.class, defaultInstance().constructType(String.class), setType); Map<String, Set<TenantState>> tenantsByServiceMap = objectMapper.readValue(config, type); final Map<String, String> tenants = new HashMap<>(); for (TenantState tenant: tenantsByServiceMap.getOrDefault(applicationName, emptySet())) { for (String host : hosts) { tenants.put(tenant.getName() + "." + host, tenant.getName().toUpperCase()); } } this.tenants = tenants; }
private Collection<Object> deserializeWithRetry(JsonParser p, DeserializationContext ctxt, JavaType contentType) throws IOException { final CollectionType collectionType = ctxt.getTypeFactory().constructCollectionType(Collection.class, contentType); try { return p.getCodec().readValue(p, collectionType); } catch (JsonMappingException e) { // attempt to read the value as string final String escapedString = p.getValueAsString(); // stop here if value could not be read if (isNull(escapedString)) { throw ctxt.instantiationException(Collection.class, "Read null value when attempting to deserialize " + collectionType.toString()); } // un-escape double quotes String unescapedString = escapedString.replaceAll("\"", "\""); // and attempt to parse again return new ObjectMapper().readValue(unescapedString, collectionType); } }
/** * 反序列化复杂Collection如List<Bean> * * @param <L> the type parameter * @param <E> the type parameter * @param jsonString the json string * @param collectionClass the collection class * @param elementClass the element class * @return 转换失败时返回 null */ public static <L extends Collection<E>, E> L fromJson(String jsonString, Class<L> collectionClass, Class<E> elementClass) { if (!StringUtils.hasText(jsonString)) { return null; } try { CollectionType type = mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass); return mapper.readValue(jsonString, type); } catch (Exception e) { (new JsonUtil()).logger.error(e.getMessage(), e); return null; } }
/** * Helper method for deserializing a chat JSON response to a collection of objects. * * @param jsonStr * The chat JSON response. * @param mapElement * Chat JSON responses are actually maps with a single element. This argument is * the value of the element to pull out from the map. * @param colClassElements * The types of objects that the collection object will contain. * @param objMapper * The JSON object mapper used to deserialize the JSON string. * @return A collection of elements of type <code>colClassElements</code>. */ private <T> Collection<T> deserializeJsonStr(String jsonStr, String mapElement, Class<T> colClassElements, ObjectMapper objMapper) { Map<String, Collection<T>> re; try { TypeFactory typeFactory = objMapper.getTypeFactory(); CollectionType type = typeFactory.constructCollectionType(List.class, colClassElements); MapType thetype = typeFactory.constructMapType(HashMap.class, typeFactory.constructType(String.class), type); re = objMapper.readValue(jsonStr, thetype); } catch (IOException e) { LOG.error("Got exception when trying to deserialize list of {}", colClassElements, e); return Lists.newArrayListWithExpectedSize(0); } return re.get(mapElement); }
@Override public void setupModule(final SetupContext context) { super.setupModule(context); context.addBeanDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<?> modifyCollectionDeserializer(final DeserializationConfig config, final CollectionType type, final BeanDescription beanDesc, final JsonDeserializer<?> deserializer) { if (deserializer instanceof CollectionDeserializer) { return new ListDeserializer((CollectionDeserializer) deserializer); } else { return super.modifyCollectionDeserializer(config, type, beanDesc, deserializer); } } }); }
@Test public void testCustomDeserializerForCustomLists() throws Exception { final CloseableHttpResponse response = mock(CloseableHttpResponse.class); when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE); when(response.getEntity()).thenReturn(new StringEntity("{results: [{field : \"SomeValue\"}], results_count: 1}")); final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response); final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); final Class<? extends CollectionType> clazzListOfTestPojo = new ObjectMapper().getTypeFactory().constructCollectionType(List.class, TestPojo.class).getClass(); final RESTServiceConnector connector = new RESTServiceConnector.Builder() .client(restClient) .classToDeserializerEntry(clazzListOfTestPojo, new CustomListDeserializer<TestPojoDeserializer>()) .build(); connector.executeRetrieveObject(TestPojo.class, "/somepath"); }
private Map<String, ContainerQuota> getChangedContainers( final String quotaContainers ) throws java.io.IOException { Map<String, ContainerQuota> changedContainersFiltered = new HashMap<>(); TypeFactory typeFactory = mapper.getTypeFactory(); CollectionType arrayType = typeFactory.constructCollectionType( ArrayList.class, ChangedContainerDto.class ); List<ChangedContainerDto> changedContainers = mapper.readValue( quotaContainers, arrayType ); for ( ChangedContainerDto cont : changedContainers ) { ContainerQuotaDto containerQuotaDto = cont.getQuota(); ContainerSize containerSize = containerQuotaDto.getContainerSize(); ContainerQuota defaultQuota = ContainerSize.getDefaultContainerQuota( containerSize ); if ( containerSize == ContainerSize.CUSTOM ) { defaultQuota = containerQuotaDto.getContainerQuota(); } changedContainersFiltered.put( cont.getHostId(), defaultQuota ); } return changedContainersFiltered; }
public Object unmarshal(Exchange exchange, InputStream stream) throws Exception { // is there a header with the unmarshal type? Class<?> clazz = unmarshalType; String type = exchange.getIn().getHeader(JacksonConstants.UNMARSHAL_TYPE, String.class); if (type == null && isAllowJmsType()) { type = exchange.getIn().getHeader("JMSType", String.class); } if (type != null) { clazz = exchange.getContext().getClassResolver().resolveMandatoryClass(type); } if (collectionType != null) { CollectionType collType = objectMapper.getTypeFactory().constructCollectionType(collectionType, clazz); return this.objectMapper.readValue(stream, collType); } else { return this.objectMapper.readValue(stream, clazz); } }
public Object unmarshal(Exchange exchange, InputStream stream) throws Exception { // is there a header with the unmarshal type? Class<?> clazz = unmarshalType; String type = exchange.getIn().getHeader(JacksonXMLConstants.UNMARSHAL_TYPE, String.class); if (type == null && isAllowJmsType()) { type = exchange.getIn().getHeader("JMSType", String.class); } if (type != null) { clazz = exchange.getContext().getClassResolver().resolveMandatoryClass(type); } if (collectionType != null) { CollectionType collType = xmlMapper.getTypeFactory().constructCollectionType(collectionType, clazz); return this.xmlMapper.readValue(stream, collType); } else { return this.xmlMapper.readValue(stream, clazz); } }
@Override public void convertAndSaveFeatures( final String testRunId, final InputStream featureStream, final Optional<String> group, final boolean dryRun, final boolean onlyNewScenarii, final boolean mergeOnlyNewPassedScenarii) { final CollectionType featureListJavaType = objectMapper.getTypeFactory().constructCollectionType(List.class, ReportFeature.class); try { final List<ReportFeature> reportFeatures = objectMapper.readValue(featureStream, featureListJavaType); for (final ReportFeature reportFeature : reportFeatures) { convertAndSaveFeature(testRunId, reportFeature, group, dryRun, onlyNewScenarii, mergeOnlyNewPassedScenarii); } } catch (final IOException e) { throw new IllegalStateException("Can't parse report feature stream", e); } }
/** * @param host * @param port * @param collection * @return * The latest segment available at the ThirdEye server. * @throws IOException */ public static long getLatestTime(String host, short port, String collection) throws IOException { String urlString = "http://" + host + ":" + port + "/collections/" + collection + "/segments"; URL url = new URL(urlString); final CollectionType listType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, SegmentDescriptor.class); List<SegmentDescriptor> segments = OBJECT_MAPPER.readValue(new InputStreamReader(url.openStream(), "UTF-8"), listType); DateTime latestDataTime = null; for (SegmentDescriptor segment : segments) { if (segment.getEndDataTime() != null && (latestDataTime == null || segment.getEndDataTime().compareTo(latestDataTime) > 0)) { latestDataTime = segment.getEndDataTime(); } } return latestDataTime.getMillis(); }
@Override public JavaType typeFromId(DatabindContext context, String id) { DeserializationContext ctx = (DeserializationContext) context; Map<String, Class> map = (Map) ctx.getAttribute("secucardobjectmap"); Class type = map.get(id); JavaType javatype; if (type == null) { javatype = MapType.construct(HashMap.class, SimpleType.construct(String.class), SimpleType.construct(Object.class)); } else { javatype = SimpleType.construct(type); } if (JsonToken.END_ARRAY.equals(ctx.getParser().getCurrentToken())) { // it is expected to get called here when reading the last token. javatype = CollectionType.construct(ArrayList.class, javatype); } return javatype; }
@Override public JsonDeserializer<?> findCollectionDeserializer(CollectionType type, DeserializationConfig config, BeanDescription beanDesc, TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) throws JsonMappingException { Class<?> raw = type.getRawClass(); if (CollectionF.class.isAssignableFrom(raw)) { if (Option.class.isAssignableFrom(raw)) { return new OptionDeserializer(type, elementTypeDeserializer, elementDeserializer); } if (ListF.class.isAssignableFrom(raw)) { return new ListFDeserializer(type, elementTypeDeserializer, elementDeserializer); } if (SetF.class.isAssignableFrom(raw)) { return new SetFDeserializer(type, elementTypeDeserializer, elementDeserializer); } return new ListFDeserializer(type, elementTypeDeserializer, elementDeserializer); } return null; }
/** Reads data source names from Druid. */ Set<String> tableNames() { final Map<String, String> requestHeaders = ImmutableMap.of("Content-Type", "application/json"); final String data = null; final String url = coordinatorUrl + "/druid/coordinator/v1/metadata/datasources"; if (CalcitePrepareImpl.DEBUG) { System.out.println("Druid: table names" + data + "; " + url); } try (InputStream in0 = post(url, data, requestHeaders, 10000, 1800000); InputStream in = traceResponse(in0)) { final ObjectMapper mapper = new ObjectMapper(); final CollectionType listType = mapper.getTypeFactory().constructCollectionType(List.class, String.class); final List<String> list = mapper.readValue(in, listType); return ImmutableSet.copyOf(list); } catch (IOException e) { throw new RuntimeException(e); } }
@Override public Set<PackageVersion> getRepoIndex(IRepoProvider provider) { RepoEntry indexEntry = provider.getEntry(IndexFileIndexer.INDEX_FILE); if (indexEntry != null) { if (!indexEntry.hasChanged(this.latest)) { return null; } this.latest = indexEntry; try { String indexString = StreamUtils.copyToString(provider.getEntryStream(IndexFileIndexer.INDEX_FILE), Charset.forName("UTF-8")); CollectionType indexType = CollectionType.construct(Set.class, SimpleType.construct(PackageVersion.class)); return this.mapper.readValue(indexString, indexType); } catch (IOException e) { throw new RuntimeException("Failed to read index", e); } } throw new RuntimeException("Didn't find index file"); }
@Test public void serderJson1() throws IOException { final ObjectMapper mapper = new ObjectMapper(); final CollectionType type = mapper.getTypeFactory().constructCollectionType(List.class, Container.class); final List<Container> containers = testRoundTrip(RemoteApiVersion.VERSION_1_22, "containers/json/filter1.json", type ); assertThat(containers.size(), equalTo(1)); final Container container = containers.get(0); assertThat(container.getImageId(), equalTo("sha256:0cb40641836c461bc97c793971d84d758371ed682042457523e4ae701efe7ec9")); assertThat(container.getSizeRootFs(), equalTo(1113554L)); final ContainerHostConfig hostConfig = container.getHostConfig(); assertThat(hostConfig, notNullValue()); assertThat(hostConfig.getNetworkMode(), equalTo("default")); }
@Override public JsonSerializer<?> modifyCollectionSerializer(SerializationConfig config, CollectionType valueType, BeanDescription beanDesc, JsonSerializer<?> serializer) { if (valueType.getRawClass() == ArrayList.class) { return new IiifIndexedListSerializer((IndexedListSerializer) serializer, config.getTypeFactory()); } return super.modifyCollectionSerializer(config, valueType, beanDesc, serializer); }
private LinkedHashSet<String> getPersistedCache() { String serialized = prefs.getString(EMOJI_LRU_PREFERENCE, "[]"); try { CollectionType collectionType = TypeFactory.defaultInstance() .constructCollectionType(LinkedHashSet.class, String.class); return JsonUtils.getMapper().readValue(serialized, collectionType); } catch (IOException e) { Log.w(TAG, e); return new LinkedHashSet<>(); } }
public CustomResultMatcher containsExactly(Object... expected) { matchers.add(result -> { CollectionType valueType = objectMapper.getTypeFactory().constructCollectionType(List.class, expectedClass); List<Object> actual = objectMapper.readValue(result.getResponse().getContentAsByteArray(), valueType); assertThat(actual).containsExactly(expected); }); return this; }
@Test @WithMockUser("user123") public void testFindProfileConnectedApps() throws Exception { final UserEntity user = new UserEntity().setUsername("user123"); final OAuth2ClientEntity client = new OAuth2ClientEntity().setId("client123").setName("client123"); final UserOAuth2ClientApprovalEntity approval1 = new UserOAuth2ClientApprovalEntity() .setUser(user) .setClient(client) .setScope("scope1") .setApprovalStatus(Approval.ApprovalStatus.APPROVED); final UserOAuth2ClientApprovalEntity approval2 = new UserOAuth2ClientApprovalEntity() .setUser(user) .setClient(client) .setScope("scope2") .setApprovalStatus(Approval.ApprovalStatus.DENIED); when(profileService.findOAuth2ClientApprovalByUsername("user123")).thenReturn(Arrays.asList(approval1, approval2)); MockHttpServletRequestBuilder request = get("/api/profile/connected-apps") .contentType(MediaType.APPLICATION_JSON); MockHttpServletResponse response = mockMvc.perform(request) .andDo(document("user-profile-connected-apps-view")) .andReturn() .getResponse(); assertThat(response.getStatus()).isEqualTo(200); CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, UserOAuth2ClientApprovalRestData.class); List<UserOAuth2ClientApprovalRestData> returnedData = objectMapper .readValue(response.getContentAsByteArray(), collectionType); assertThat(returnedData).hasSize(1); UserOAuth2ClientApprovalRestData restData = returnedData.get(0); assertThat(restData.getClientId()).isEqualTo(client.getId()); assertThat(restData.getClientName()).isEqualTo(client.getName()); assertThat(restData.getUsername()).isEqualTo(user.getUsername()); ImmutableMap<String, Approval.ApprovalStatus> scopeAndStatus = restData.getScopeAndStatus(); assertThat(scopeAndStatus).hasSize(2); assertThat(scopeAndStatus).containsEntry(approval1.getScope(), approval1.getApprovalStatus()); assertThat(scopeAndStatus).containsEntry(approval2.getScope(), approval2.getApprovalStatus()); verify(profileService).findOAuth2ClientApprovalByUsername("user123"); }
@Test @SneakyThrows public void testAddTenants() { ObjectMapper om = new ObjectMapper(); mockMvc.perform(post("/api/tenants/entity") .content("xm") .contentType(MediaType.TEXT_PLAIN)) .andExpect(status().is2xxSuccessful()); mockMvc.perform(post("/api/tenants/entity") .content("ecs") .contentType(MediaType.TEXT_PLAIN)) .andExpect(status().is2xxSuccessful()); mockMvc.perform(post("/api/tenants/entity") .content("demo") .contentType(MediaType.TEXT_PLAIN)) .andExpect(status().is2xxSuccessful()); mockMvc.perform(post("/api/tenants/entity") .content("olololo") .contentType(MediaType.TEXT_PLAIN)) .andExpect(status().is2xxSuccessful()); mockMvc.perform(post("/api/tenants/entity") .content("test2") .contentType(MediaType.TEXT_PLAIN)) .andExpect(status().is2xxSuccessful()); mockMvc.perform(get("/api/tenants/entity") .contentType(MediaType.TEXT_PLAIN)) .andDo(mvc -> { CollectionType stringSet = om.getTypeFactory().constructCollectionType(Set.class, TenantState.class); Set<TenantState> value = om.readValue(mvc.getResponse().getContentAsString(), stringSet); assertTrue(value.contains(new TenantState("xm",""))); assertTrue(value.contains(new TenantState("ecs", ""))); assertTrue(value.contains(new TenantState("demo", ""))); assertTrue(value.contains(new TenantState("olololo", ""))); assertTrue(value.contains(new TenantState("test2", ""))); assertFalse(value.contains(new TenantState("test123123", ""))); }) .andExpect(status().is2xxSuccessful()); }
public static <T> List<T> jsonToList(String json, Class<T> klass) { CollectionType ct = sMapper.getTypeFactory().constructCollectionType(ArrayList.class, klass); try { return sMapper.readValue(json, ct); } catch (Exception e) { e.printStackTrace(); } return new ArrayList<>(); }
@Override protected final void onAsyncStream(InputStream stream) throws Exception { ObjectMapper mapper = getObjectMapper(); CollectionType ct = mapper.getTypeFactory().constructCollectionType(ArrayList.class, mClass); mResults = mapper.readValue(stream, ct); if (mResults == null) { throw new Exception("Can't parse Json into a list"); } }
/** * Create new address. * * @param chain chain. * @param n world count. * @return new address. * @throws IOException */ public static Address createNew(@NotNull final String chain, final int n) throws IOException { if (n <= 0) throw new IllegalArgumentException("n must be positive"); final File file = new File("src/main/resources/words.json"); final ObjectMapper mapper = new ObjectMapper(); final CollectionType type = mapper.getTypeFactory().constructCollectionType(List.class, String.class); final List<String> wordList = mapper.readValue(file, type); final StringBuilder words = new StringBuilder(); final Random rand = new Random(); for (int i = 0; i < n; i++) { int index = rand.nextInt(wordList.size()); words.append(wordList.get(index)); if (i < n - 1) { words.append(" "); } wordList.remove(index); } final String seed = words.toString(); byte[] seedEncode = seed.getBytes(StandardCharsets.UTF_8); final byte[] seedHash = Crypto.hashChain(seedEncode); final byte[] accountSeedHash = Crypto.sha256(seedHash); final Curve25519KeyPairGenerator gen = new Curve25519KeyPairGenerator(); final KeyPair pair = gen.generateKeyPair(accountSeedHash); return generate(pair, seed, chain); }
public <C extends Collection<T>, T> C deserialize(final String jsonString, final Class<C> collectionType, final Class<T> elementType) { try { final CollectionType javaType = OBJECT_MAPPER.getTypeFactory() .constructCollectionType(collectionType, elementType); return OBJECT_MAPPER.readValue(jsonString, javaType); } catch (IOException e) { LOGGER.error(UNEXPECTED_EXCEPTION, e); return null; } }
public <T> T getObjectFromJson(String json, CollectionType classType) { try { return mObjectMapper.readValue(json, classType); } catch (Exception e) { ExceptionTracker.track(e); } return null; }
List<T> load(Class<?> resultType) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(fileName); if (file.exists()) { CollectionType mapType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, resultType); return Collections.synchronizedList(objectMapper.readValue(file, mapType)); } else { return Collections.synchronizedList(new ArrayList<>()); } }
public <S> List<S> getResponseJsonList(Class<S> clazz) { assertGone(); if (clazz == null) { return null; } CollectionType listType = jacksonObjectMapper.getTypeFactory().constructCollectionType(List.class, clazz); try { return jacksonObjectMapper.readValue(responseBody, listType); } catch (IOException e) { throw new RuntimeException(e); } }
/** * 非常麻烦 * * @param jsonString * @param clazz * @param <T> * @return */ public static <T> List<T> parseArray(String jsonString, Class<T> clazz) { //注册一种类型 // 非常麻烦 ,不同的应用,需要注册不同的类型,直接用 fast json 吧 CollectionType javaType = objectMapper.getTypeFactory().constructCollectionType(List.class, clazz); try { return objectMapper.readValue(jsonString, javaType); } catch (IOException e) { e.printStackTrace(); return null; } }
private List<IdModel> readJsonStr(String json) throws JsonProcessingException, IOException { ObjectMapper mapper = new ObjectMapper(); final JsonNode response = mapper.readTree(json); final CollectionType collectionType = TypeFactory.defaultInstance().constructCollectionType(List.class, IdModel.class); List<Object> object = mapper.readerFor(collectionType).readValues(response.traverse()).readAll(); @SuppressWarnings("unchecked") List<IdModel> result = (List<IdModel>) object.get(0); return result; }
private <A> List<A> readValue(JsonParser jsonParser, CollectionType type){ try { return mapper.readValue(jsonParser, type); } catch (IOException e) { throw Throwables.propagate(e); } }
FmlModInfo extractFmlModInfo(InputStream in) throws IOException { final Path tempModInfo = Files.createTempFile("fmlmodinfo", null); Files.copy(in, tempModInfo, StandardCopyOption.REPLACE_EXISTING); String detectedCharset = UniversalDetector.detectCharset(tempModInfo.toFile()); if (detectedCharset == null) { detectedCharset = filesSettings.getFallbackCharset(); } final Charset cs = Charset.forName(detectedCharset); String modinfoJson = fixUnquotedVersionStrings(new String(Files.readAllBytes(tempModInfo), cs)); modinfoJson = fixMissingCommas(modinfoJson); try { return objectMapper.readValue(modinfoJson, FmlModInfo.class); } catch (JsonParseException | JsonMappingException e) { LOG.debug("Failed to parse as full structure, will try list only", e); CollectionType modListEntriesType = objectMapper.getTypeFactory() .constructCollectionType(ArrayList.class, FmlModListEntry.class); ArrayList<FmlModListEntry> entries = objectMapper.readValue(modinfoJson, modListEntriesType); return new FmlModInfo(entries); } finally { Files.delete(tempModInfo); } }
protected TotallylazyCollectionDeserializer(CollectionType type, TypeDeserializer typeDeser, JsonDeserializer<?> deser) { super(type); _containerType = type; _typeDeserializerForValue = typeDeser; _valueDeserializer = deser; }
/** * We have plenty of collection types to support... */ @Override public JsonDeserializer<?> findCollectionDeserializer(CollectionType type, DeserializationConfig config, BeanDescription beanDesc, TypeDeserializer elementTypeDeserializer, JsonDeserializer<?> elementDeserializer) throws JsonMappingException { return new SequenceDeserializer(type, elementTypeDeserializer, elementDeserializer); }
/** * Setter method to interact with the DB, because the Java standard deserialization doesn't work. * * @param nodesAsString * The Nodes of the machine as JSON string. */ @JsonIgnore public void setNodesDB(String nodesAsString) { try { CollectionType valueType = OBJECT_MAPPER.getTypeFactory() .constructCollectionType(List.class, Integer.class); this.nodes = OBJECT_MAPPER.readValue(nodesAsString, valueType); } catch (IOException e) { e.printStackTrace(); } }
/** * Setter method to interact with the DB, because the Java standard deserialization doesn't work. * * @param edgesAsString * The Edges of the machine as JSON string. */ @JsonIgnore public void setEdgesDB(String edgesAsString) { try { CollectionType valueType = OBJECT_MAPPER.getTypeFactory() .constructCollectionType(List.class, CompactMealyTransitionProxy.class); this.edges = OBJECT_MAPPER.readValue(edgesAsString, valueType); } catch (IOException e) { e.printStackTrace(); } }
@Override public void onRequest() { String term = this.getComponent().getRequest().getQueryParameters().getParameterValue("term").toString(); if (!Strings.isEmpty(term)) { StringWriter sw = new StringWriter(); try { J value = null; Integer index = 0; List<J> toSerializeObjects = Lists.newArrayList(); for (I item : getValues(term)) { item = HibernateUtils.unwrap(item); index++; value = newAutocompleteJson(index, item, getComponent().getLocale()); toSerializeObjects.add(value); } // il est important d'utiliser un typeReference sinon les paramètres de sérialisation // polymorphiques de J ne seront pas appliqués. CollectionType collectionType = OBJECT_MAPPER.getTypeFactory() .constructCollectionType(List.class, getJsonType()); OBJECT_MAPPER.writerFor(collectionType).writeValue(sw, toSerializeObjects); } catch (IOException e) { throw new WicketRuntimeException(e); } RequestCycle.get().scheduleRequestHandlerAfterCurrent( new TextRequestHandler("application/json", "utf-8", sw.toString())); } }