通过组合两个字符串动态生成Json

时间:2019-05-20 10:36:56

标签: java string list dictionary java-8

我有2个字符串,即

String str1 = "a,b,c,d,e,f,g,h,i,j,k";
String str2 = "1,2,3,4,5,6";

我想在json下面生成2个字符串以上的

[{
        "A": "a",
        "B": "b",
        "C": "c",
        "ONE": "1",
        "Two": "2"
    },

{
    "D": "d",
    "E": "c",
    "F": "e",
    "Three": "3",
    "Four": "4"
},

{
    "G": "d",
    "H": "c",
    "I": "e",
    "Five": "5",
    "Six": "6"
}

]

我的东西不是动态的,因为我知道将第一个字符串的3个间隔除以第二个字符串的2个间隔,但是在某些情况下我不知道字符串的长度会增加:

String str1 = "a,b,c,d,e,f,g,h,i,j,k";
    String str2 = "1,2,3,4,5,6";

    Map<Object, Object> m1 = new LinkedHashMap<>();
    ObjectMapper ob = new ObjectMapper();
    String[] split1;




    if(str1 != null) {

        split1 = str1.split(",");
        System.out.println("sasdasd : "+split1);
        if(split1.length > 0) {

            m1.put("A", split1[0]);
            m1.put("B", split1[1]);
            m1.put("C", split1[2]);

        }

        split1 = str2.split(",");
        if(split1.length > 0) {

            m1.put("ONE", split1[0]);
            m1.put("TWO", split1[1]);

        }

        String msg = ob.writeValueAsString(m1);
        System.out.println("M1:"+m1);

    }

0 个答案:

没有答案