1. 首页
  2. Java

如何使用 fastjson 将JSON字符串解析为复杂结构,如嵌套 List, 嵌套 Map

1.转为 Map<String, Double>

String str = "";
Map<String, Double> map = JSON.parseObject(str, new TypeReference<Map<String, Double>>(){});

2.转为 List<String>

String str = "";
List<String> arr = JSON.parseObject(str, new TypeReference<List<String>>(){});

3.转为双重List

String str = "";
Type type = new TypeReference<List<List<UserData>>>() {}.getType();
List<List<UserData>> res = JSON.parseObject(str, type);

4.转为具体的某个类

Type type = new TypeReference<UserResponse<UserRuntimeException>>() {}.getType();
UserResponse<UserRuntimeException> exception = null;
try {
    exception = JSON.parseObject(str, type);
} catch (Exception ignored) {
}
if (exception != null && exception.getAlert() != null && exception.getAlert().getMessage() != null && exception.getAlert().getMessage().getContent() != null) {
    throw UserRuntimeException.of(exception.getAlert().getMessage().getContent().toString());
}

TOP