Skip to content

Instantly share code, notes, and snippets.

@upangka
Created November 6, 2019 10:34
Show Gist options
  • Save upangka/911634b09c297954675cfe70cc26b6e6 to your computer and use it in GitHub Desktop.
Save upangka/911634b09c297954675cfe70cc26b6e6 to your computer and use it in GitHub Desktop.
jackson对数据的序列化与反序列化的强大

将 “【1,2,3】” 转化为List [1,2,3]

public static <T> T json2Object(String json, TypeReference<T> reference, boolean failOnUnknownProperties) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        if (failOnUnknownProperties) {
            MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        }
        try {
            T t = MAPPER.readValue(json, reference);
            if (failOnUnknownProperties) {
                MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
            }
            return t;
        } catch (IOException e) {
            log.error("数据 [{}] 反序列化失败", json);
            throw new BusinessException(JsonResultCode.CODE_JACKSON_DESERIALIZATION_FAILED);
        }
    }

使用方式

		String arr = "[1,2,3]";
		List<Integer> json2Object = Util.json2Object(arr,new TypeReference<List<Integer>>(){}, false);
		System.out.println(json2Object);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment