Converting Map into json

前端 未结 4 1876
长情又很酷
长情又很酷 2021-02-15 16:40

I have Map in java like this :

{card_switch=Master, issuing_bank=ICCI, card_Type=DebitCard}

I\'m using the s

4条回答
  •  醉酒成梦
    2021-02-15 17:13

    You can also try something like this with Gson Library:

    package com.stackoverflow.works;
    
    import java.lang.reflect.Type;
    import java.util.HashMap;
    import java.util.Map;
    
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;
    
    /*
     * @Author: sarath_sivan
     */
    
    public class MapToJsonConverter {
    
        /*
         * @Description: Method to convert Map to JSON String
         * @param: map Map 
         * @return: json String
         */
        public static String convert(Map map) {
            Gson gson = new Gson();
            String json = gson.toJson(map);
            return json;
        }
    
        /*
         * @Description: Method to convert JSON String to Map
         * @param: json String 
         * @return: map Map 
         */
        public static Map revert(String json) {
            Gson gson = new Gson();
            Type type = new TypeToken>(){}.getType();
            Map map = gson.fromJson(json, type);
            return map;
        }
    
        /*
         * @Description: Method to print elements in the Map
         * @param: map Map 
         * @return: void 
         */
        public static void printMap(Map map) {
            for (String key : map.keySet()) {
                System.out.println("map.get(\"" + key + "\") = " + map.get(key));
            }
        }
    
        /*
         * @Description: Method to print the JSON String
         * @param: json String 
         * @return: void 
         */
        public static void printJson(String json) {
            System.out.println("json = " + json);
        }
    
        /*
         * @Description: Main method to test the JSON-MAP convert/revert logic
         */
        public static void main(String[] args) {
            Map paymentCards = new HashMap();
            paymentCards.put("card_switch", "Master");
            paymentCards.put("issuing_bank", "ICCI");
            paymentCards.put("card_Type", "DebitCard");
    
            String json = convert(paymentCards); //converting Map to JSON String
            System.out.println("Map to JSON String");
            System.out.println("******************");
            printJson(json); 
    
            System.out.println();
    
            paymentCards = revert(json); //converting JSON String to Map
            System.out.println("JSON String to Map");
            System.out.println("******************");
            printMap(paymentCards);
        }
    
    }
    

    The output look like this:

    Output

提交回复
热议问题