Conversion between Map and JSON

1 Adding a Dependency

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

2 test

2.1 turn the Map JSON

    / / 1. Turn the map json
    @Test
    public void testJson01(a){
        / / 1. Turn the 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);
    }
Copy the code

2.2 turn the String Map

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

2.3 a JSON String

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

2.4 turn the Map JSON

    / / 4. Turn the map JSON
    @Test
    public void testJSON04(a){
        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()); }}Copy the code

2.5 turn JSON String

    / / 5. Turn a json String
    @Test
    public void testJSON05(a){
        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);
    }
Copy the code