Map和JSON之间的转化

5,114 阅读1分钟

Map和JSON之间的转化

1 添加依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

2 测试

2.1 Map转JSON

    //1.map转json
    @Test
    public void testJson01(){
        //1.Map转JSON
        Map<String,Object> map=new HashMap<>();
        map.put("A","a");
        map.put("B","b");
        JSONObject jsonObject = new JSONObject(map);
        System.out.println(jsonObject);
    }

image-20210917194051922

2.2 Map转String

    //2.map转Spring
    @Test
    public void testJson02(){
        Map<String,Object> map=new HashMap<>();
        map.put("A","a");
        String s = JSONObject.toJSONString(map);
        System.out.println(s);
    }

image-20210917194231304

2.3 JSON转String

    //3.JSON转String
    @Test
    public void testJSON03(){
        JSONObject json=new JSONObject();
        json.put("A","A");
        json.put("B","B");
        String s = json.toJSONString();
        System.out.println(s);
    }

image-20210917194317591

2.4 JSON转Map

    //4.JSON转map
    @Test
    public void testJSON04(){
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("A","a");
        jsonObject.put("B","b");
        Map<String,Object> map= (Map<String,Object>)jsonObject;
        for(Map.Entry<String,Object> entry:map.entrySet()){
            System.out.println(entry.getKey()+"--"+entry.getValue());
        }
    }

image-20210917194413943

2.5 String转JSON

    //5.String转json
    @Test
    public void testJSON05(){
        String str="{\"username\":\"abc\",\"pwd\":\"123\"}";
        JSONObject json = JSONObject.parseObject(str);
        Object username = json.get("username");
        System.out.println(username);
        Object pwd = json.get("pwd");
        System.out.println(pwd);
    }

image-20210917194459286