有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何将java map对象格式化为groovy map

我正在尝试使用java生成groovy代码,我将在groovyscript引擎上部署java,用于动态JSON数据映射。在做这件事的时候,我坚持这个问题。我正在用java生成map对象 以下面的格式

 finalmap-->   {ENVIRONMENT={TEST=Functions.split(input.env.TEST,"/"), CO2=input.env.CO2}}

因此,为了将其转换为groovy脚本映射对象,我使用了以下代码

groovyScript.append("Map output ="+"\n"+new JSONObject(finalmap).toString(2).replace("\"", "").replace("{", "[").replace("}", "]").replace("`", "\"")+";");
String result=new String(groovyScript).replaceAll("\\\\", "\"");

此代码将地图对象转换为:

Map out =
[ENVIRONMENT: [
  TEST: Functions.split(input.env.TEST,"/"),
  CO2: input.env.CO2
]];

但是,当我使用很多替换函数时,如果键或值具有替换字符,那么它也将替换该字符

所以,不用replace函数,我们就可以得到输出


共 (2) 个答案

  1. # 1 楼答案

    试试map.inspect()

    def m = [a: 1, b: '1']
    assert m.inspect() == "['a':1, 'b':'1']"
    
  2. # 2 楼答案

    我使用recusrion做了以下操作。缩进可以使用字符串格式

    public static String mapFormatter(Map<String, Object> lhm1,String result) throws ParseException {
               result=result+"["+"\n";
               for (Map.Entry<String, Object> entry : lhm1.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
               if (value instanceof Map) {
                    Map<String, Object> subMap = (Map<String, Object>)value;
                    result=result+key+" : ";
                    result=result+mapFormatter(subMap,"");
                }
               else {
                    result=result+key+" : "+value+","+"\n";
                }
            }
               result=result.replaceAll(",$", "")+"]"+"\n";
            return result;
        }
    
    public static void main(String[] args) throws ParseException {
    Map<String,Object> map3 = new HashMap<>();
            map3.put("at","a");
            map3.put("bt","b");
            Map<String,Object> map2 = new HashMap<>();
            map2.put("test",map3);
            Map<String,Object> map = new HashMap<>();
            map.put("map",map2);
            map.put("id",123);
            System.out.println(map);
            System.err.println(mapFormatter(map));
    }
    

    输出: 这个没有格式化,使用字符串格式我们可以包含标识

    [
        id : 123,
        map : [
        test : [
        bt : b,
        at : a
        ]
        ]
        ]