json 转化Map

json 转化Map

  • 正常的fastjson和sf.json是无法的几行代码之内将json转化成Map
  • 当时Gson就可以满足当前的需求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Data
public class Test {

private String id;

private String name;

}

public class GsonTest {

public static void main(String[] args) {
...
Map<String, List<Test>> testMap = new HashMap<>();
// 装Map
String testMapJsonStr = "";

// 利用Gson 转化Map
Gson gson = new Gson();
Map<String, List<Test>> newTestMap = gson.fromJson(dzdmJson, new TypeToken<Map<String, List<Test>>>(){}.getType());
}

}
1
2
3
public static final <T> T toObject(String jsonString, TypeReference<T> type) {
return JSON.parseObject(jsonString, type);
}

2 2018 0127 补充

  • 在使用Gson的时候,发现不能格式化带有int的json字符串。报错如下:
    image

  • 示例json

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    3: {
    "id": 3,
    "name": "背叛国家罪",
    "open": false,
    "pId": 2,
    "title": "背叛国家罪"
    },
    4: {
    "id": 4,
    "name": "分裂国家罪",
    "open": false,
    "pId": 2,
    "title": "分裂国家罪"
    },
  • 解决方案

    使用fastjson的类库进行格式化

    1
    JSON.parseObject(str, new TypeReference<Map<Integer, Bean>>(){});