Java 类com.fasterxml.jackson.core.type.TypeReference 实例源码

项目:echo    文件:ResourceDirectory.java   
private Map<String, String> populateDataFlows(Object item){
    Map<String, String> mapping = new HashMap<String, String>();
    LinkedHashMap<String,Object> linkedItem = (LinkedHashMap<String,Object>) item;
    ArrayList<LinkedHashMap>linkedMap = (ArrayList<LinkedHashMap>) linkedItem.get("item-metadata");
    String mappingAsString = null;
    for(LinkedHashMap hashmap : linkedMap){
        switch((String)hashmap.get("rel")){
        case "Mapping JSON": 
            mappingAsString = (String)hashmap.get("val");
            break;
        }
    }
    mappingAsString = mappingAsString.replaceAll( "\\\\\"","\"");
    ObjectMapper mapper = new ObjectMapper();
    try {
        mapping = mapper.readValue(mappingAsString, new TypeReference<Map<String, String>>(){});
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return mapping;
}
项目:clemon    文件:ResourceController.java   
@SystemControllerLog(description="权限管理-资源列表")
@RequestMapping(value = "/data")
@ResponseBody
public String data(String params,HttpSession session) {
    try {
        ObjectMapper om = new ObjectMapper();
        Map<String, Object> map = new HashMap<String, Object>();
        // 当前只查询管理员
        if (!StringUtils.isEmpty(params)) {
            // 参数处理
            map = om.readValue(params, new TypeReference<Map<String, Object>>() {});
        }
        PagerModel<Resource > pg = resourceService.findPaginated(map);
        // 序列化查询结果为JSON
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total", pg.getTotal());
        result.put("rows", pg.getData());
        return om.writeValueAsString(result);
    } catch (Exception e) {
        e.printStackTrace();
        return "{ \"total\" : 0, \"rows\" : [] }";
    }
}
项目:fresco_floodlight    文件:StorageNotifyResource.java   
@Post("json")
public Map<String,Object> notify(String entity) throws Exception {
    List<StorageSourceNotification> notifications = null;
    ObjectMapper mapper = new ObjectMapper();
    notifications = 
        mapper.readValue(entity, 
                new TypeReference<List<StorageSourceNotification>>(){});

    IStorageSourceService storageSource = 
        (IStorageSourceService)getContext().getAttributes().
            get(IStorageSourceService.class.getCanonicalName());
    storageSource.notifyListeners(notifications);

    HashMap<String, Object> model = new HashMap<String,Object>();
    model.put("output", "OK");
    return model;
}
项目:javaOIDCMsg    文件:JsonNodeClaimTest.java   
@Test
public void shouldThrowIfAnExtraordinaryExceptionHappensWhenParsingAsGenericMap() throws Exception {
    JsonNode value = mock(ObjectNode.class);
    when(value.getNodeType()).thenReturn(JsonNodeType.OBJECT);

    JsonNodeClaim claim = (JsonNodeClaim) claimFromNode(value);
    JsonNodeClaim spiedClaim = spy(claim);
    ObjectMapper mockedMapper = mock(ObjectMapper.class);
    when(spiedClaim.getObjectMapper()).thenReturn(mockedMapper);
    JsonParser mockedParser = mock(JsonParser.class);
    when(mockedMapper.treeAsTokens(value)).thenReturn(mockedParser);
    when(mockedParser.readValueAs(ArgumentMatchers.any(TypeReference.class))).thenThrow(IOException.class);

    exception.expect(JWTDecodeException.class);
    spiedClaim.asMap();
}
项目:nakadi-producer-spring-boot-starter    文件:EventTransmissionService.java   
public NakadiEvent mapToNakadiEvent(final EventLog event) {
    final NakadiEvent nakadiEvent = new NakadiEvent();

    final NakadiMetadata metadata = new NakadiMetadata();
    metadata.setEid(convertToUUID(event.getId()));
    metadata.setOccuredAt(event.getCreated());
    metadata.setFlowId(event.getFlowId());
    nakadiEvent.setMetadata(metadata);

    HashMap<String, Object> payloadDTO;
    try {
        payloadDTO = objectMapper.readValue(event.getEventBodyData(), new TypeReference<LinkedHashMap<String, Object>>() { });
    } catch (IOException e) {
        log.error("An error occurred at JSON deserialization", e);
        throw new UncheckedIOException(e);
    }

    nakadiEvent.setData(payloadDTO);

    return nakadiEvent;
}
项目:flowing-retail    文件:MessageListener.java   
@StreamListener(target = Sink.INPUT)
@Transactional
public void messageReceived(String messageJson) throws Exception {
  Message<JsonNode> message = new ObjectMapper().readValue( //
      messageJson, //
      new TypeReference<Message<JsonNode>>() {});

  String type = "Event";
  if (message.getMessageType().endsWith("Command")) {
    type = "Command";
  }

  PastEvent event = new PastEvent( //
      type, //
      message.getMessageType(), //
      message.getTraceId(), //
      message.getSender(), //
      message.getPayload().toString());

  // save
  LogRepository.instance.addEvent(event);

  // and probably send to connected websocket (TODO: Not a good place for the code here!)
  simpMessageTemplate.convertAndSend("/topic/events", event);
}
项目:flowing-retail    文件:MessageListener.java   
/**
 * Handles incoming OrderPlacedEvents. 
 * 
 *  Using the conditional {@link StreamListener} from 
 * https://github.com/spring-cloud/spring-cloud-stream/blob/master/spring-cloud-stream-core-docs/src/main/asciidoc/spring-cloud-stream-overview.adoc
 * in a way close to what Axion
 *  would do (see e.g. https://dturanski.wordpress.com/2017/03/26/spring-cloud-stream-for-event-driven-architectures/)
 */
@StreamListener(target = Sink.INPUT, 
    condition="payload.messageType.toString()=='OrderPlacedEvent'")
@Transactional
public void orderPlacedReceived(String messageJson) throws JsonParseException, JsonMappingException, IOException {
  Message<Order> message = new ObjectMapper().readValue(messageJson, new TypeReference<Message<Order>>(){});
  Order order = message.getPayload();

  System.out.println("New order placed, start flow. " + order);

  // persist domain entity
  repository.persistOrder(order);    

  // and kick of a new flow instance
  camunda.getRuntimeService().createMessageCorrelation(message.getMessageType())
    .processInstanceBusinessKey(message.getTraceId())
    .setVariable("orderId", order.getId())
    .correlateWithResult();
}
项目:trellis    文件:AbstractLdpResourceTest.java   
@Test
public void testPrefer() throws IOException {
    final Response res = target(RESOURCE_PATH).request()
        .header("Prefer", "return=representation; include=\"" + Trellis.PreferServerManaged.getIRIString() + "\"")
        .accept("application/ld+json; profile=\"http://www.w3.org/ns/json-ld#compacted\"").get();

    assertEquals(OK, res.getStatusInfo());

    final String entity = IOUtils.toString((InputStream) res.getEntity(), UTF_8);
    final Map<String, Object> obj = MAPPER.readValue(entity, new TypeReference<Map<String, Object>>(){});

    assertTrue(obj.containsKey("@context"));
    assertTrue(obj.containsKey("title"));
    assertFalse(obj.containsKey("mode"));
    assertTrue(obj.containsKey("created"));

    assertEquals("A title", (String) obj.get("title"));
}
项目:jetfuel-instagram    文件:Follows.java   
@Override
protected void mainFlow(UsecaseExecution<Parameters, InstagramResponse<List<User>>> execution) throws Exception {

    String endpoint = String.format(
            "https://api.instagram.com/v1/users/%s/follows?access_token=%s",
            execution.params.user_id,
            execution.params.access_token);

    URL url = new URL(endpoint);
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    try {
        execution.result = MAPPER.readValue(is, new TypeReference<InstagramResponse<List<User>>>() {
        });
    } finally {
        is.close();
    }
    execution.result_type = UsecaseResultType.SUCCESS;
}
项目:jobson    文件:TestJobsAPI.java   
@Test
public void testCanGetJobInputs() throws IOException {
    final APIJobRequest req = REQUEST_AGAINST_FIRST_SPEC;

    final JobId jobId = generateAuthenticatedRequest(RULE, HTTP_JOBS_PATH)
            .post(json(req))
            .readEntity(APIJobCreatedResponse.class)
            .getId();

    final Response jobInputsResponse =
            generateAuthenticatedRequest(RULE, jobResourceSubpath(jobId + "/inputs"))
            .get();

    assertThat(jobInputsResponse.getStatus()).isEqualTo(OK);

    final String responseJson = jobInputsResponse.readEntity(String.class);

    final Map<JobExpectedInputId, JsonNode> inputsReturned =
            readJSON(responseJson, new TypeReference<Map<JobExpectedInputId, JsonNode>>() {});

    assertThat(inputsReturned).isEqualTo(req.getInputs());
}
项目:projectindoorweb    文件:EverythingControllerTest.java   
private long processEvaluationFileForBuilding(long buildingId) throws Exception {

        mockMvc.perform(MockMvcRequestBuilders.fileUpload("/position/processEvalFiles")
                .file(evaluationFile)
                .param("buildingIdentifier", String.valueOf(buildingId)))
                .andExpect(status().isOk());

        ResultActions getEvalFileResultActions = mockMvc.perform(get("/position/getEvalFilesForBuildingId?" +
                "buildingIdentifier=" + buildingId));
        getEvalFileResultActions.andExpect(status().isOk());
        String getEvalFileResult = getEvalFileResultActions.andReturn().getResponse().getContentAsString();
        List<GetEvaluationFilesForBuilding> getEvaluationFilesForBuilding = (List<GetEvaluationFilesForBuilding>)
                this.objectMapper.readValue(getEvalFileResult, new TypeReference<List<GetEvaluationFilesForBuilding>>() {
                });
        assertTrue("The returned list of type " + GetEvaluationFilesForBuilding.class.getSimpleName() + " had an unexpected size.",
                getEvaluationFilesForBuilding.size() == 1);

        return getEvaluationFilesForBuilding.get(0).getId();

    }
项目:rubenlagus-TelegramBots    文件:GetFile.java   
@Override
public File deserializeResponse(String answer) throws TelegramApiRequestException {
    try {
        ApiResponse<File> result = OBJECT_MAPPER.readValue(answer,
                new TypeReference<ApiResponse<File>>(){});
        if (result.getOk()) {
            return result.getResult();
        } else {
            throw new TelegramApiRequestException("Error getting file", result);
        }
    } catch (IOException e) {
        throw new TelegramApiRequestException("Unable to deserialize response", e);
    }
}
项目:devops-cstack    文件:JsonConverter.java   
public static List<EnvironmentVariable> getEnvironmentVariables(String response) {
    List<EnvironmentVariable> environmentVariables = new ArrayList<>();
    ObjectMapper mapper = new ObjectMapper();
    try {
        environmentVariables = mapper.readValue(response, new TypeReference<List<EnvironmentVariable>>() {
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
    return environmentVariables;
}
项目:hibernate-types    文件:JacksonUtil.java   
public static <T> T fromString(String string, TypeReference<T> typeReference) {
    try {
        return OBJECT_MAPPER.readValue(string, typeReference);
    } catch (IOException e) {
        throw new IllegalArgumentException("The given string value: " + string + " cannot be transformed to Json object", e);
    }
}
项目:nuls    文件:JSONUtils.java   
/**
 * json string convert to map with javaBean
 */
public static <T> Map<String, T> json2map(String jsonStr, Class<T> clazz)
        throws Exception {
    Map<String, Map<String, Object>> map = OBJECT_MAPPER.readValue(jsonStr,
            new TypeReference<Map<String, T>>() {
            });
    Map<String, T> result = new HashMap<String, T>();
    for (Map.Entry<String, Map<String, Object>> entry : map.entrySet()) {
        result.put(entry.getKey(), map2pojo(entry.getValue(), clazz));
    }
    return result;
}
项目:c4sg-services    文件:SlackClientServiceImpl.java   
protected <T> T readValue(JsonNode node, String findPath, TypeReference<?> typeReference) {
    try {
        if (findPath != null) {
            if (!node.has(findPath))
                return null;
            node = node.findPath(findPath);
        }
        return mapper.readValue(node.toString(), typeReference);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
项目:rubenlagus-TelegramBots    文件:GetChatMember.java   
@Override
public ChatMember deserializeResponse(String answer) throws TelegramApiRequestException {
    try {
        ApiResponse<ChatMember> result = OBJECT_MAPPER.readValue(answer,
                new TypeReference<ApiResponse<ChatMember>>(){});
        if (result.getOk()) {
            return result.getResult();
        } else {
            throw new TelegramApiRequestException("Error getting chat member", result);
        }
    } catch (IOException e) {
        throw new TelegramApiRequestException("Unable to deserialize response", e);
    }
}
项目:rubenlagus-TelegramBots    文件:SendDocument.java   
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
    try {
        ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
                new TypeReference<ApiResponse<Message>>(){});
        if (result.getOk()) {
            return result.getResult();
        } else {
            throw new TelegramApiRequestException("Error sending document", result);
        }
    } catch (IOException e) {
        throw new TelegramApiRequestException("Unable to deserialize response", e);
    }
}
项目:plugin-prov-aws    文件:ProvAwsPriceImportResource.java   
/**
 * Read the spot region to the new format from an external JSON file.
 * 
 * @throws IOException
 *             When the JSON mapping file cannot be read.
 */
@PostConstruct
public void initSpotToNewRegion() throws IOException {
    mapSpotToNewRegion.putAll(objectMapper.readValue(
            IOUtils.toString(new ClassPathResource(SPOT_TO_NEW_REGION_FILE).getInputStream(), StandardCharsets.UTF_8),
            new TypeReference<Map<String, String>>() {
                // Nothing to extend
            }));
}
项目:cloudterm    文件:TerminalSocket.java   
private Map<String, String> getMessageMap(TextMessage message) {
    try {
        Map<String, String> map = new ObjectMapper().readValue(message.getPayload(), new TypeReference<Map<String, String>>() {
        });

        return map;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new HashMap<>();
}
项目:GitHub    文件:ObjectMappedTest.java   
@Test
public void jsonValueSingletonRoundtrip() throws Exception {
  String json = "[1.4]";

  List<JsonValueCreator.Singleton> values =
      OBJECT_MAPPER.readValue(json, new TypeReference<List<JsonValueCreator.Singleton>>() {});

  check(OBJECT_MAPPER.writeValueAsString(values)).is(json);
}
项目:GitHub    文件:JacksonParserFactory.java   
@Override
public HashMap<String, String> getStringMap(Object object) {
    try {
        TypeReference<HashMap<String, String>> typeRef
                = new TypeReference<HashMap<String, String>>() {
        };
        ObjectWriter objectWriter = mapper.writerFor(object.getClass());
        return mapper.readValue(objectWriter.writeValueAsString(object), typeRef);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new HashMap<>();
}
项目:elasticsearch-jdbc    文件:JacksonJSONAdapter.java   
@Override
public JSONArray parseArray(String json) {
    try {
        List<Object> value = mapper.readValue(json, new TypeReference<List<Object>>() {
        });
        return new JacksonJSONArray(value);
    } catch (IOException e) {
        throw new JSONException(e);
    }
}
项目:liberty-outage-reporter    文件:CloudantLocationStore.java   
private static String readURLFromKubeSecretsFile(String secretsFile) throws IOException {
    String secretsJson = readKubeSecretsFiles(secretsFile);
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map;

    // convert JSON string to Map
    map = mapper.readValue(secretsJson, new TypeReference<Map<String, String>>(){});
    String url = (String) map.get("url");
    url = url.replaceFirst("https", "http"); //Temporary hack until certificates are figured out.
    System.out.println("url: " + url);
    return url;
}
项目:neto    文件:NetoJsonStringToMapWebSocketDecoder.java   
@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {

    NetoExceptionMessage exceptionMessage;

    Map<String, Object> data = null;

    try {

        logger.error("{}", frame);

        if (frame instanceof PingWebSocketFrame) {
            ctx.write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        if (frame instanceof BinaryWebSocketFrame) {
            // Echo the frame
            ctx.write(frame.retain());
            return;
        }

        if (frame instanceof TextWebSocketFrame) {
            data = objectMapper.readValue(((TextWebSocketFrame) frame).text(), new TypeReference<Map<String, Object>>() {});
        } else {
            exceptionMessage = new NetoExceptionMessage("Unsupported : " + frame.getClass().getName());
            data = objectMapper.convertValue(exceptionMessage, Map.class);
        }
    } catch (Exception e) {
        exceptionMessage = new NetoExceptionMessage(e.getMessage());
        data = objectMapper.convertValue(exceptionMessage, Map.class);
    }

    ctx.fireChannelRead(data);
}
项目:java-benchmark    文件:DeserJackson.java   
@Setup(Level.Trial)
public void benchSetup(BenchmarkParams params) {
    objectMapper = new ObjectMapper();
    objectMapper.registerModule(new AfterburnerModule());
    typeReference = new TypeReference<TestObject>() {
    };
    testJSON = TestObject.createTestJSON();
}
项目:fresco_floodlight    文件:AbstractSyncManager.java   
@Override
public <K, V>IStoreClient<K, V>
    getStoreClient(String storeName, 
                   TypeReference<K> keyType, 
                   TypeReference<V> valueType)
                           throws UnknownStoreException {
    return getStoreClient(storeName, null, keyType, 
                          null, valueType, null);
}
项目:Practical-Real-time-Processing-and-Analytics    文件:ElasticSearchBolt.java   
public Map<String,Object> convertStringtoMap(String fieldValue) throws JsonParseException, JsonMappingException, IOException {
    System.out.println("Orignal value  "+ fieldValue);
    Map<String,Object> convertedValue = new HashMap<>();
    Map<String,Object> readValue = mapper.readValue(fieldValue, new TypeReference<Map<String,Object>>() {});

    convertedValue.put("ambient_temperature", Double.parseDouble(String.valueOf(readValue.get("ambient_temperature"))));
    convertedValue.put("photosensor", Double.parseDouble(String.valueOf(readValue.get("photosensor"))));
    convertedValue.put("humidity", Double.parseDouble(String.valueOf(readValue.get("humidity"))));
    convertedValue.put("radiation_level", Integer.parseInt(String.valueOf(readValue.get("radiation_level"))));
    convertedValue.put("sensor_uuid", readValue.get("sensor_uuid"));
    convertedValue.put("timestamp", new Date());

    System.out.println("Converted value  "+ convertedValue);
    return convertedValue;
}
项目:activiti-analytics-spring-boot    文件:AnalyticsConfig.java   
@SuppressWarnings("unchecked")
@Bean
public MappingConfiguration mappingConfiguration() {
    logger.debug("creating mappingConfiguration bean");
    MappingConfiguration mappingConf = new MappingConfiguration();
    try {
        URL endStateConfigUrl = Resources.getResource("mappingconfig/end-state-mapping.json");
        String endStateConfigJSON = Resources.toString(endStateConfigUrl, Charsets.UTF_8);
        mappingConf.setEndStateConfigMap((List<Map<String, Object>>) new ObjectMapper()
                .readValue(endStateConfigJSON, new TypeReference<List<Object>>() {
                }));

        URL allProcessConfigUrl = Resources.getResource("mappingconfig/all-processes-mapping-config.json");
        String allProcessConfigJSON = Resources.toString(allProcessConfigUrl, Charsets.UTF_8);
        mappingConf.setAllProcessConfigMap((Map<String, Object>) new ObjectMapper().readValue(allProcessConfigJSON,
                new TypeReference<Map<String, Object>>() {
                }));

        URL allTasksConfigUrl = Resources.getResource("mappingconfig/all-tasks-mapping-config.json");
        String allTasksConfigJSON = Resources.toString(allTasksConfigUrl, Charsets.UTF_8);
        mappingConf.setAllTasksConfigMap((Map<String, Object>) new ObjectMapper().readValue(allTasksConfigJSON,
                new TypeReference<Map<String, Object>>() {
                }));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return mappingConf;
}
项目:fresco_floodlight    文件:AbstractSyncManager.java   
/**
 * The "real" version of getStoreClient that will be called by all
 * the others
 * @param storeName the store name
 * @param keyClass the key class
 * @param keyType the key type
 * @param valueClass the value class
 * @param valueType the value type
 * @param resolver the inconsistency resolver
 * @return a {@link DefaultStoreClient} using the given parameters.
 * @throws UnknownStoreException
 */
public <K, V> IStoreClient<K, V>
        getStoreClient(String storeName, 
                       Class<K> keyClass, 
                       TypeReference<K> keyType,
                       Class<V> valueClass, 
                       TypeReference<V> valueType, 
                       IInconsistencyResolver<Versioned<V>> resolver)
                               throws UnknownStoreException {
    IStore<ByteArray,byte[]> store = getStore(storeName);
    IStore<K, V> serializingStore;
    if (valueType != null && keyType != null) {
        serializingStore = 
                new JacksonStore<K, V>(store, keyType, valueType);
    } else if (valueClass != null && keyClass != null) {
        serializingStore = 
                new JacksonStore<K, V>(store, keyClass, valueClass);
    } else {
        throw new IllegalArgumentException("Must include type reference" +
                " or value class");
    }

    DefaultStoreClient<K, V> storeClient =
            new DefaultStoreClient<K, V>(serializingStore,
                    resolver,
                    this,
                    keyClass,
                    keyType);
    return storeClient;
}
项目:rubenlagus-TelegramBots    文件:UnpinChatMessage.java   
@Override
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
    try {
        ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
                new TypeReference<ApiResponse<Boolean>>(){});
        if (result.getOk()) {
            return result.getResult();
        } else {
            throw new TelegramApiRequestException("Error unpinning chat message", result);
        }
    } catch (IOException e) {
        throw new TelegramApiRequestException("Unable to deserialize response", e);
    }
}
项目:rkt-launcher    文件:List.java   
@Override
default ListOutput parse(final String output) {
  try {
    final java.util.List<io.honnix.rkt.launcher.model.Image> images =
        Json.deserializeSnakeCase(
            output,
            new TypeReference<java.util.List<io.honnix.rkt.launcher.model.Image>>() {
            });
    return ListOutput.builder()
        .images(images == null ? ImmutableList.of() : images)
        .build();
  } catch (IOException e) {
    throw new RktUnexpectedOutputException("failed parsing JSON output", e);
  }
}
项目:qpp-conversion-tool    文件:ApmEntityIds.java   
/**
 * Given the file name, returns a {@link Set} of {@link String}s from the file.
 *
 * @param fileName The file to parse.
 * @return Set of Strings.
 */
private static Set<String> grabConfiguration(final String fileName) {
    TypeReference<Set<String>> setOfStringsType = new TypeReference<Set<String>>() {};

    InputStream apmEntityIdsInput = ClasspathHelper.contextClassLoader().getResourceAsStream(fileName);

    return JsonHelper.readJson(apmEntityIdsInput, setOfStringsType);
}
项目:qpp-conversion-tool    文件:JsonHelper.java   
/**
 * Read json file and return object type specified
 *
 * @param json content
 * @param valueType object type representation
 * @param <T> generic class type
 * @return Object of specified type
 * @throws JsonReadException if problems arise while attempting to parse the json input stream
 */
public static <T> T readJson(InputStream json, TypeReference<T> valueType) {
    T returnValue;
    try {
        returnValue = new ObjectMapper().readValue(json, valueType);
    } catch (IOException ex) {
        throw new JsonReadException(PROBLEM_PARSING_JSON, ex);
    }
    return returnValue;
}
项目:redg    文件:JsonFileNameProvider.java   
public JsonFileNameProvider(final File jsonFile) throws IOException {
    Objects.requireNonNull(jsonFile);
    ObjectMapper mapper = new ObjectMapper();
    TypeReference<HashMap<String, JsonTableNameData>> typeReference = new TypeReference<HashMap<String, JsonTableNameData>>() {
    };
    mappings = mapper.readValue(jsonFile, typeReference);
}
项目:hibernate-types    文件:JacksonUtil.java   
public static <T> T fromString(String string, TypeReference<T> typeReference) {
    try {
        return OBJECT_MAPPER.readValue(string, typeReference);
    } catch (IOException e) {
        throw new IllegalArgumentException("The given string value: " + string + " cannot be transformed to Json object", e);
    }
}
项目:Tenable.io-SDK-for-Java    文件:InputControl.java   
/**
 * Sets list.
 *
 * @param list the list
 */
public void setList( List<?> list ) {
    ObjectMapper mapper = new ObjectMapper();

    try {
        this.list = mapper.readValue(list.toString(), new TypeReference<List<Dropdown>>() {} );
    } catch( Exception e) {
        this.list = new ArrayList<String>();
        this.list = list;
    }
}
项目:rubenlagus-TelegramBots    文件:SendGame.java   
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
    try {
        ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
                new TypeReference<ApiResponse<Message>>(){});
        if (result.getOk()) {
            return result.getResult();
        } else {
            throw new TelegramApiRequestException("Error sending game", result);
        }
    } catch (IOException e) {
        throw new TelegramApiRequestException("Unable to deserialize response", e);
    }
}
项目:cmc-claim-store    文件:JsonMapper.java   
public <T> T fromJson(String value, TypeReference<T> typeReference) {
    try {
        return objectMapper.readValue(value, typeReference);
    } catch (IOException e) {
        throw new InvalidApplicationException(
            String.format(DESERIALISATION_ERROR_MESSAGE, typeReference.getType()), e
        );
    }
}
项目:StubbornJava    文件:JsonTest.java   
@Test
public void parseShouldNotFailOnExtraFields() {
    // {{start:fromJsonExtraFields}}
    String rawJson = Resources.asString("json-test/extra-fields.json");
    Message message = Json.serializer().fromJson(rawJson, new TypeReference<Message>() {});
    // {{end:fromJsonExtraFields}}

    assertEquals("Happy New Year!", message.getMessage());
    assertEquals(LocalDate.of(2017, 1, 1), message.getDate());

    String actualJson = Json.serializer().toString(message);
    assertEquals(message, Json.serializer().fromJson(actualJson, new TypeReference<Message>() {}));
}