1. 程式人生 > 實用技巧 >java 使用fast json 與 Map List互相轉換

java 使用fast json 與 Map List互相轉換

import com.alibaba.fastjson.JSON;
import com.imooc.vo.Person;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JsonMapListUtil {
    public static void main(String[] args) {

        // Map 與 Json 互轉
        Map<Integer,Integer> integerMap=Map.of(11,22,44,55,66,77,100,200);
        String integerMapString
= JSON.toJSONString(integerMap,true); System.out.println("integerMapString:"+integerMapString); //預設型別 會轉換成JSONObject型別,即 Map<String,Object>的子類 Map<String,Object> objMap=JSON.parseObject(integerMapString); System.out.println("objMap: "+objMap); //objMap: {"66":77,"11":22,"44":55,"100":200} 此時的key型別為String,與之前不一致
// 後面加 Map.class 轉換為 Map型別 Map<Integer,Integer> objMap22=JSON.parseObject(integerMapString,Map.class); // Map<Object,Object> objMap22=JSON.parseObject(integerMapString,Map.class); System.out.println("objMap22: "+objMap22); // {66=77, 100=200, 11=22, 44=55} 此時結果是正確的,與之前的型別一致
for (Map.Entry<Integer,Integer> entry:objMap22.entrySet()){ System.out.println(entry.getKey() instanceof Integer); //全部 true System.out.println(entry.getValue() instanceof Integer);//全部 true } // List 與 Json 互轉 List<Person> people=new ArrayList<>(); people.add(new Person("zhangsan")); people.add(new Person("zhangsan22")); people.add(new Person("zhangsan33")); String peopleJson= JSON.toJSONString(people,true); System.out.println("peopleJson:"+peopleJson); List<Person> people1=JSON.parseArray(peopleJson,Person.class); System.out.println("people1:"+people1); List<String> pp=List.of("11","22","33"); String ppJson=JSON.toJSONString(pp,true); System.out.println("ppJson:"+ppJson); List<String> pp1=JSON.parseArray(ppJson,String.class); System.out.println("pp1:"+pp1); System.out.println("pp:"+pp); List<Integer> ppp=List.of(11,22,33); String pppJson=JSON.toJSONString(ppp,true); System.out.println("pppJson:"+pppJson); // List<Integer> ppp1=JSON.parseArray(pppJson,Integer.class); List<Object> ppp1=JSON.parseArray(pppJson); System.out.println("ppp1:"+ppp1); System.out.println("ppp:"+ppp); for (Object i:ppp1){ System.out.println(i instanceof Integer); System.out.println(i instanceof String); } } }