Java Code Examples for org.codehaus.jackson.type.TypeReference

The following examples show how to use org.codehaus.jackson.type.TypeReference. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: bbs   Source File: JsonUtils.java    License: GNU Affero General Public License v3.0 8 votes vote down vote up
/**
 * JSON串转换为Java泛型对象,可以是各种类型,此方法最为强大。用法看测试用例。
 * @param <T>
 * @param jsonString JSON字符串
* @param tr TypeReference,例如: new TypeReference< List<FamousUser> >(){}
 * @return List对象列表
 */
public static <T> T toGenericObject(String jsonString, TypeReference<T> tr) {
 
    if (jsonString == null || "".equals(jsonString)) {
        return null;
    } else {
        try {
            return objectMapper.readValue(jsonString, tr);
        } catch (Exception e) {
         //	e.printStackTrace();
         if (logger.isErrorEnabled()) {
         	logger.error("JSON串转换为Java泛型对象",e);
		    }
        
        }
    }
    return null;
}
 
Example 2
Source Project: jira-rest-client   Source File: ProjectService.java    License: Apache License 2.0 6 votes vote down vote up
public Project getProjectDetail(String idOrKey) throws IOException {
	if (client == null)
		throw new IllegalStateException("HTTP Client not Initailized");
	
	client.setResourceName(Constants.JIRA_RESOURCE_PROJECT + "/" + idOrKey);
	ClientResponse response = client.get();
				
	String content = response.getEntity(String.class);	
	
	ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);
	
	TypeReference<Project> ref = new TypeReference<Project>(){};
	Project prj = mapper.readValue(content, ref);
	
	return prj;
}
 
Example 3
@Override
public Map<String, Country> loadCountries() throws Exception {
	ClassPathResource classPathResource = new ClassPathResource("countries.json");
	InputStreamReader reader = new InputStreamReader(classPathResource.getInputStream());
	try {
		Map<String, String> countryMap = new ObjectMapper().readValue(classPathResource.getInputStream(), new TypeReference<Map<String, String>>() {});
		Map<String, Country> countries = new LinkedHashMap<String, Country>();
		for (String key : countryMap.keySet()) {
			Country country = new Country();
			country.setName(WordUtils.capitalizeFully(key));
			country.setCode(countryMap.get(key));
			countries.put(country.getCode(), country);
		}
		return countries;
	} finally {
		reader.close();
	}
}
 
Example 4
Source Project: samza   Source File: TaskPartitionAssignmentManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads the task partition assignments from the underlying storage layer.
 * @return the task partition assignments.
 */
public Map<SystemStreamPartition, List<String>> readTaskPartitionAssignments() {
  try {
    Map<SystemStreamPartition, List<String>> sspToTaskNamesMap = new HashMap<>();
    Map<String, byte[]> allMetadataEntries = metadataStore.all();
    for (Map.Entry<String, byte[]> entry : allMetadataEntries.entrySet()) {
      SystemStreamPartition systemStreamPartition = deserializeSSPFromJson(entry.getKey());
      String taskNamesAsJson = valueSerde.fromBytes(entry.getValue());
      List<String> taskNames = taskNamesMapper.readValue(taskNamesAsJson, new TypeReference<List<String>>() { });
      sspToTaskNamesMap.put(systemStreamPartition, taskNames);
    }
    return sspToTaskNamesMap;
  } catch (Exception e) {
    throw new SamzaException("Exception occurred when reading task partition assignments.", e);
  }
}
 
Example 5
Source Project: samza   Source File: DiagnosticsStreamMessage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to use {@link SamzaObjectMapper} to deserialize {@link ContainerModel}s.
 * {@link SamzaObjectMapper} provides several conventions and optimizations for deserializing containerModels.
 * @return
 */
private static Map<String, ContainerModel> deserializeContainerModelMap(
    String serializedContainerModel) {
  Map<String, ContainerModel> containerModelMap = null;
  ObjectMapper samzaObjectMapper = SamzaObjectMapper.getObjectMapper();

  try {
    if (serializedContainerModel != null) {
      containerModelMap = samzaObjectMapper.readValue(serializedContainerModel, new TypeReference<Map<String, ContainerModel>>() {
      });
    }
  } catch (IOException e) {
    LOG.error("Exception in deserializing container model ", e);
  }

  return containerModelMap;
}
 
Example 6
Source Project: jira-rest-client   Source File: IssueService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of all issue types visible to the user
 *
 * @return List list of IssueType
 *
 * @throws IOException json decoding failed
 */
public List<IssueType> getAllIssueTypes() throws IOException {

    client.setResourceName(Constants.JIRA_RESOURCE_ISSUETYPE);

    ClientResponse response = client.get();
    String content = response.getEntity(String.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);

    TypeReference<List<IssueType>> ref = new TypeReference<List<IssueType>>() {
    };
    List<IssueType> issueTypes = mapper.readValue(content, ref);

    return issueTypes;
}
 
Example 7
Source Project: olat   Source File: RepositoryEntriesITCase.java    License: Apache License 2.0 5 votes vote down vote up
protected List<RepositoryEntryVO> parseRepoArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<RepositoryEntryVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 8
Source Project: olat   Source File: OlatJerseyTestCase.java    License: Apache License 2.0 5 votes vote down vote up
protected List<ErrorVO> parseErrorArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<ErrorVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 9
Source Project: olat   Source File: CourseITCase.java    License: Apache License 2.0 5 votes vote down vote up
protected List<UserVO> parseUserArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<UserVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 10
Source Project: RDFS   Source File: ClusterJspHelper.java    License: Apache License 2.0 5 votes vote down vote up
/** Get the map corresponding to the JSON string */
private static Map<String, Map<String, Object>> getNodeMap(String json)
    throws IOException {
  TypeReference<Map<String, Map<String, Object>>> type = 
    new TypeReference<Map<String, Map<String, Object>>>() { };
  return mapper.readValue(json, type);
}
 
Example 11
Source Project: metrics   Source File: MetricsResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testListMetrics() {
    MetricManager.getIMetricManager().clear();
    MetricManager.getCounter("product", MetricName.build("middleware.product.provider"));
    MetricManager.getMeter("test", MetricName.build("shared.carts.my_cart").level(MetricLevel.CRITICAL)).mark();
    MetricManager.getMeter("test", MetricName.build("shared.carts.my_cart")
            .level(MetricLevel.CRITICAL).tagged("source", "taobao")).mark();

    GenericType<Map<String, Object>> genericType = new GenericType<Map<String, Object>>(){};
    Map<String, Object> result = target("metrics/list").request()
            .accept(MediaType.APPLICATION_JSON_TYPE).get(genericType);

    Assert.assertEquals("success should be true", true, result.get("success"));
    Assert.assertTrue("data should be a map", result.get("data") instanceof Map);

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Set<MetricObject>> data =
            mapper.convertValue(result.get("data"), new TypeReference<Map<String, Set<MetricObject>>>(){});
    Assert.assertTrue(data.get("product").contains(MetricObject.named("middleware.product.provider.count")
            .withType(MetricObject.MetricType.COUNTER).withLevel(MetricLevel.NORMAL).build()));
    Assert.assertEquals(".count/.m1/.m5/.m15/.bucket_count/qps * 2 = 12", 12, data.get("test").size());
    Assert.assertTrue("shared.carts.my_cart.m1 should be CRITICAL level",
            data.get("test").contains(MetricObject.named("shared.carts.my_cart.m1")
            .withLevel(MetricLevel.CRITICAL).withType(MetricObject.MetricType.GAUGE).build()));
    Map<String, String> tags = new HashMap<String, String>();
    tags.put("source", "taobao");
    Assert.assertTrue(data.get("test").contains(MetricObject.named("shared.carts.my_cart.m1").withTags(tags)
            .withLevel(MetricLevel.CRITICAL).withType(MetricObject.MetricType.GAUGE).build()));
}
 
Example 12
Source Project: DataSphereStudio   Source File: FlowRestfulApi.java    License: Apache License 2.0 5 votes vote down vote up
@POST
@Path("/saveFlow")
public Response saveFlow(@Context HttpServletRequest req, JsonNode json) throws DSSErrorException, IOException, AppJointErrorException {
    Long flowID = json.get("id").getLongValue();
    String jsonFlow = json.get("json").getTextValue();
    Long projectVersionID = json.get("projectVersionID").getLongValue();
    String userName = SecurityFilter.getLoginUsername(req);
    String comment = json.get("comment") == null?"保存更新":json.get("comment").getTextValue();
    List<Op> ops = mapper.readValue(json.get("ops"), new TypeReference<List<Op>>(){});
    publishManager.checkeIsPublishing(projectVersionID);
    String version =flowService.saveFlow(flowID,jsonFlow,comment,userName,projectVersionID,ops);
    return Message.messageToResponse(Message.ok().data("flowVersion",version));
}
 
Example 13
Source Project: ambari-logsearch   Source File: AliasUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static HashMap<String, Object> getJsonFileContentFromClassPath(String fileName) {
  ObjectMapper mapper = new ObjectMapper();
  try (InputStream inputStream = AliasUtil.class.getClassLoader().getResourceAsStream(fileName)) {
    return mapper.readValue(inputStream, new TypeReference<HashMap<String, Object>>() {});
  } catch (IOException e) {
    logger.error("Error occurred during loading alias json file: {}", e);
  }
  return new HashMap<String, Object>();
}
 
Example 14
Source Project: ml-blog   Source File: JsonUtil.java    License: MIT License 5 votes vote down vote up
public static <T> T string2Obj(String json, TypeReference<T> typeReference) {
    if (json == null || "".equals(json) || typeReference == null) {
        return null;
    }

    try {
        return typeReference.getType().equals(String.class) ? (T) json : objectMapper.readValue(json, typeReference);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 15
Source Project: maven-framework-project   Source File: JsonFile2Map.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {

		try {

			ObjectMapper mapper = new ObjectMapper();

			// read JSON from a file
			Map<String, Object> map = mapper.readValue(
					new File("src/main/resources/user.json"),
					new TypeReference<Map<String, Object>>() {
					});

			System.out.println(map.get("name"));
			System.out.println(map.get("age"));

			@SuppressWarnings("unchecked")
			ArrayList<String> list = (ArrayList<String>) map.get("messages");

			for (String msg : list) {
				System.out.println(msg);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
 
Example 16
private Map<String, String> loadCurrencyNames() throws Exception {
	logger.info("loading currency names");
	ClassPathResource classPathResource = new ClassPathResource("usable-currencies.json");
	InputStreamReader reader = new InputStreamReader(classPathResource.getInputStream());
	try {
		return new ObjectMapper().readValue(classPathResource.getInputStream(), new TypeReference<Map<String, String>>() {});
	} finally {
		reader.close();
	}
}
 
Example 17
Source Project: mmall-kay-Java   Source File: JsonUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 通过 TypeReference 指定要返回的集合对象
 * @param str
 * @param typeReference
 * @param <T>
 * @return
 */
public static <T> T string2obj(String str, TypeReference<T> typeReference){
    if (StringUtils.isEmpty(str) || typeReference == null) {
        return null;
    }
    try {
        return (T)(typeReference.getType().equals(String.class) ? str : objectMapper.readValue(str, typeReference));
    } catch (Exception e) {
        log.warn("parse string2obj warn",e);
        return null;
    }
}
 
Example 18
Source Project: rocket-console   Source File: JsonUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * String => Object
 *
 * @param str
 * @param typeReference
 * @return
 */
public static <T> T string2Obj(String str, TypeReference<T> typeReference) {
    if (Strings.isNullOrEmpty(str)|| typeReference == null) {
        return null;
    }
    str = escapesSpecialChar(str);
    try {
        return (T) (typeReference.getType().equals(String.class) ? str : objectMapper.readValue(str, typeReference));
    } catch (Exception e) {
        logger.error("Parse String to Object error\nString: {}\nTypeReference<T>: {}\nError: {}", str,
                typeReference.getType(), e);
        return null;
    }
}
 
Example 19
Source Project: hadoop   Source File: ClusterJspHelper.java    License: Apache License 2.0 5 votes vote down vote up
/** Get the map corresponding to the JSON string */
private static Map<String, Map<String, Object>> getNodeMap(String json)
    throws IOException {
  TypeReference<Map<String, Map<String, Object>>> type = 
    new TypeReference<Map<String, Map<String, Object>>>() { };
  return mapper.readValue(json, type);
}
 
Example 20
Source Project: big-c   Source File: ClusterJspHelper.java    License: Apache License 2.0 5 votes vote down vote up
/** Get the map corresponding to the JSON string */
private static Map<String, Map<String, Object>> getNodeMap(String json)
    throws IOException {
  TypeReference<Map<String, Map<String, Object>>> type = 
    new TypeReference<Map<String, Map<String, Object>>>() { };
  return mapper.readValue(json, type);
}
 
Example 21
Source Project: sakai   Source File: ListMetadataType.java    License: Educational Community License v2.0 5 votes vote down vote up
public List<T> fromString(String string)
{
	List<T> metadataValues = new ArrayList<T>();
	try
	{

		if (string != null)
		{
			List<String> stringValues = new ObjectMapper().readValue(string, new TypeReference<List<String>>()
			{
			});

			for (String stringValue : stringValues)
			{
				T metadataValue = metadataConverter.fromString(stringValue);
				if (metadataValue != null)
					metadataValues.add(metadataValue);
			}
		}
		
	}
	catch (IOException e)
	{
		// Ignore any problems parsing them.
	}
	return metadataValues;
}
 
Example 22
Source Project: olat   Source File: GroupMgmtITCase.java    License: Apache License 2.0 5 votes vote down vote up
protected List<UserVO> parseUserArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<UserVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 23
/**
 * Reduce/Merge the KafkaTopicPartitionStatsResponse responses of a collection of host/instance into one response
 */
public static String reduceTopicPartitionStatsResponses(Map<String, String> responses, Logger logger) {
  Map<String, KafkaTopicPartitionStatsResponse> result = new HashMap<>();

  responses.forEach((instance, json) -> {
    List<KafkaTopicPartitionStatsResponse> responseList;
    try {
      responseList = JsonUtils.fromJson(json, new TypeReference<List<KafkaTopicPartitionStatsResponse>>() {
      });
    } catch (Exception e) {
      logger.error("Invalid response {} from instance {}", json, instance);
      return;
    }

    responseList.forEach(response -> {
      if (response.getTopicPartitions() == null || StringUtils.isBlank(response.getConsumerGroupId())
          || response.getDatastreams() == null) {
        logger.warn("Empty topic partition stats map from instance {}. Ignoring the result", instance);
        return;
      }

      KafkaTopicPartitionStatsResponse reducedResponse = result.computeIfAbsent(response.getConsumerGroupId(),
          k -> new KafkaTopicPartitionStatsResponse(response.getConsumerGroupId()));
      reducedResponse.getDatastreams().addAll(response.getDatastreams());

      Map<String, Set<Integer>> topicPartitions = response.getTopicPartitions();
      topicPartitions.forEach((topic, partitions) -> {
        Map<String, Set<Integer>> reducedTopicPartitions = reducedResponse.getTopicPartitions();
        Set<Integer> reducedPartitions = reducedTopicPartitions.computeIfAbsent(topic, k -> new HashSet<>());
        reducedPartitions.addAll(partitions);
      });
    });
  });

  return JsonUtils.toJson(result.values());
}
 
Example 24
private boolean testProcessTopicPartitionsStatsInternal(KafkaMirrorMakerConnector connector,
    Map<String, Set<Integer>> expected) {
  String jsonStr = connector.process(PARTITIONS);
  List<KafkaTopicPartitionStatsResponse> responseList =
      JsonUtils.fromJson(jsonStr, new TypeReference<List<KafkaTopicPartitionStatsResponse>>() {
      });

  Map<String, Set<Integer>> actual = new HashMap<>();
  responseList.forEach(response -> {
    Map<String, Set<Integer>> partitions = response.getTopicPartitions();
    actual.putAll(response.getTopicPartitions());
  });

  return actual.equals(expected);
}
 
Example 25
Source Project: brooklin   Source File: JsonUtils.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Deserialize a JSON string into an object based on a type reference.
 * This method allows the caller to specify precisely the desired output
 * type for the target object.
 * @param json JSON string
 * @param typeRef type reference of the target object
 * @param <T> type of the target object
 * @return deserialized Java object
 */
public static <T> T fromJson(String json, TypeReference<T> typeRef) {
  Validate.notNull(json, "null JSON string");
  Validate.notNull(typeRef, "null type reference");
  T object = null;
  try {
    object = MAPPER.readValue(json, typeRef);
  } catch (IOException e) {
    String errorMessage = "Failed to parse json: " + json;
    ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
  }
  return object;
}
 
Example 26
private static Map<String, String> getMetadata(CommandLine cmd, Options options) {
  if (cmd.hasOption(OptionConstants.OPT_SHORT_METADATA)) {
    return JsonUtils.fromJson(getOptionValue(cmd, OptionConstants.OPT_SHORT_METADATA, options),
        new TypeReference<Map<String, String>>() {
        });
  }
  return Collections.emptyMap();
}
 
Example 27
Source Project: samza   Source File: TestCoordinatorStreamWriter.java    License: Apache License 2.0 5 votes vote down vote up
private <T> T deserialize(byte[] bytes, TypeReference<T> reference) {
  try {
    if (bytes != null) {
      String valueStr = new String((byte[]) bytes, "UTF-8");
      return SamzaObjectMapper.getObjectMapper().readValue(valueStr, reference);
    }
  } catch (Exception e) {
    throw new SamzaException(e);
  }

  return null;
}
 
Example 28
Source Project: olat   Source File: UserMgmtITCase.java    License: Apache License 2.0 5 votes vote down vote up
protected List<UserVO> parseUserArray(final String body) {
    try {
        final ObjectMapper mapper = new ObjectMapper(jsonFactory);
        return mapper.readValue(body, new TypeReference<List<UserVO>>() {/* */
        });
    } catch (final Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 29
Source Project: samza   Source File: JsonUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Deserialize a JSON string into an object based on a type reference.
 * This method allows the caller to specify precisely the desired output
 * type for the target object.
 * @param json JSON string
 * @param typeRef type reference of the target object
 * @param <T> type of the target object
 * @return deserialized Java object
 */
public static <T> T fromJson(String json, TypeReference<T> typeRef) {
  Validate.notNull(json, "null JSON string");
  Validate.notNull(typeRef, "null type reference");
  T object;
  try {
    object = MAPPER.readValue(json, typeRef);
  } catch (IOException e) {
    String errorMessage = "Failed to parse json: " + json;
    LOG.error(errorMessage, e);
    throw new SamzaException(errorMessage, e);
  }
  return object;
}
 
Example 30
Source Project: samza   Source File: SamzaSqlRelRecordSerdeFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SamzaSqlRelRecord fromBytes(byte[] bytes) {
  try {
    ObjectMapper mapper = new ObjectMapper();
    // Enable object typing to handle nested records
    mapper.enableDefaultTyping();
    return mapper.readValue(new String(bytes, "UTF-8"), new TypeReference<SamzaSqlRelRecord>() { });
  } catch (Exception e) {
    throw new SamzaException(e);
  }
}