-
JSON字符串反序列化对象(单个对象)
@Slf4j public class TypeReferenceTest{ @Test public void parseObject(){ String jsonContent = "{\"code\":\"200\",\"message\":\"error message\",\"data\":\"hello world\"}" ; TypeReference<RestResponse<String>> typeReference = new TypeReference<String>(){} ; RestResponse<String> response = JSON.parseObject(jsonContent, typeReference); log.info("====> response : {}", response); } }
-
ObjectMapper字符串反序列化(集合)
@SpringBootTest(classes = DynamicNacosApplication.class) public class ObjectMapperTest { @Autowired private ObjectMapper objectMapper ; @Test public void collectionType() throws JsonProcessingException { String content = "...." ; CollectionType collectionType = objectMapper.getTypeFactory() .constructCollectionType(ArrayList.class, RouteDefinition.class); List<RouteDefinition> routeDefinitions = objectMapper.readValue(content, collectionType); routeDefinitions.forEach(item -> log.info("item : {}", item)); } }
-
ObjectMapper字符串反序列化(集合)
@SpringBootTest(classes = DynamicNacosApplication.class) public class ObjectMapperTest { @Autowired private ObjectMapper objectMapper ; @Test public void collectionType() throws JsonProcessingException { String content = "...." ; // other method List<RouteDefinition> infoCmds = objectMapper.readValue(jsonData, new TypeReference<List<RouteDefinition>>(){}); } }
-
RestTemplate返回值泛型转换
@Slf4j public class ParameterizedTypeReferenceTest { private RestTemplate restTemplate = new RestTemplate(); @Test public void exchange(){ String url = "http://localhost:8080/user-service/hello/index" ; ParameterizedTypeReference<RestResponse<String>> typeReference = new ParameterizedTypeReference<>() {} ; ResponseEntity<RestResponse<String>> exchange = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(null), typeReference); RestResponse<String> retValue = exchange.getBody(); log.info("ret value : {}", retValue); } @Test public void exchangeMap(){ String url = "http://localhost:8080/user-service/hello/index" ; ParameterizedTypeReference<Map<String,Object>> typeReference = new ParameterizedTypeReference<>() {} ; ResponseEntity<Map<String,Object>> exchange = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(null), typeReference); Map<String,Object> retValue = exchange.getBody(); log.info("ret value : {}", retValue); } }
TypeReference使用笔记
于 2023-09-17 14:18:39 首次发布