溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

FastJson中List、Map如何轉換使用

發(fā)布時間:2021-09-05 14:56:49 來源:億速云 閱讀:330 作者:小新 欄目:編程語言

小編給大家分享一下FastJson中List、Map如何轉換使用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

基礎類型的List、Map轉換方式

List<String>

List<String>轉為Json字符串

    List<String> strList = new ArrayList<>();
    strList.add("str1");
    strList.add("str2");

    String inputStr = JSON.toJSONString(strList);
    System.out.println(inputStr);

Json字符串轉為List<String>

    List<String> outputList = JSON.parseObject(inputStr, List.class);
    outputList.forEach(System.out::println);

Map<String, String>

Map<String, String>轉為Json字符串

	Map<String, String> strMap = new HashMap<>();
    strMap.put("key1", "value1");
    strMap.put("key2", "value2");

    String inputMap = JSON.toJSONString(strMap);
    System.out.println(inputMap);

Json字符串轉為Map<String, String>

    Map<String, String> stringMap = JSON.parseObject(inputMap, Map.class);
    stringMap.forEach((key, value) -> System.out.println(key + " : " + value));

Bean類型的List、Map轉換方式

List<Bean>

List<Bean>轉為Json字符串

    List<Bean> inputList = new ArrayList<>();
    inputList.add(new Bean(1, "po1"));
    inputList.add(new Bean(2, "po2"));
    String inputStr = JSON.toJSONString(inputList);
    System.out.println(inputStr);

Json字符串轉為List<Bean>

    List<Bean> outputList = JSON.parseArray(inputStr, Bean.class);
    outputList.forEach(po -> System.out.println(po.getNum() + " name: " + po.getName()));

Map<String, Bean>

Map<String, Bean>轉為Json字符串

    Map<String, Bean> strMap = new HashMap<>();
    strMap.put("key1", new Bean(1, "po1"));
    strMap.put("key2", new Bean(2, "po2"));
    String inputMap = JSON.toJSONString(strMap);
    System.out.println(inputMap);

Json字符串轉為Map<String, Bean>

    Map<String, JSONObject> stringMap = JSON.parseObject(inputMap, Map.class);
    stringMap.forEach((key, value) -> {
        Bean mock = JSON.parseObject(value.toJSONString(), Bean.class);
        System.out.println(key + " : " + mock.getName());
    });

Bean類型的List、Map高階轉換方式(TypeReference<T>)

使用TypeReference將Json字符串轉為List<Bean>

    Type listType = new TypeReference<List<Bean>>() {}.getType();
    List<Bean> outputList = JSON.parseObject(inputStr, listType);
    outputList.forEach(po -> System.out.println(po.getNum() + " name: " + po.getName()));

使用TypeReference將Json字符串轉為Map<String, Bean>

    Type mapType = new TypeReference<Map<String, Bean>>() {}.getType();
    Map<String, Bean> stringMap = JSON.parseObject(inputMap, mapType);
    stringMap.forEach((key, value) -> {
        System.out.println(key + " : " + value.getName());
    });

以上是“FastJson中List、Map如何轉換使用”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI