如何在Java中将格式为{a = 2,b = 5}的字符串转换为格式为{“ a”:2,“ b”:5}的JSON?

时间:2018-06-21 15:25:01

标签: java json

我在进行表情表达评估后得到{a = 2,b = 5}形式的结果。 我想将其转换为json。 我该怎么做? 请帮忙!

1 个答案:

答案 0 :(得分:-1)

这是您的解决方案:

public static void main(String[] args) {

    String something = "{a=2 ,b=5}";
    something = something.replace("{", "");
    something = something.replace("}", "");

    String[] pairs = something.split(",");
    ArrayList<String> list = new ArrayList<String>();

    for (String pair : pairs) {
        list.add(pair);
    }

    for (int i = 0; i < list.size(); i++) {
        String[] temp = list.get(i).split("=");
        temp[0] = "\"" + temp[0] + "\"";
        list.set(i, temp[0] + ":" + temp[1]);
    }
    String contents = "";
    for (int i = 0; i < list.size(); i++) {
        contents = contents + ", " + list.get(i);
    }

    contents = contents.replaceFirst(", ", "");

    contents = "{" + contents + "}";

    System.out.println("Contents: " + contents);
}

这是您的结果:

Contents: {"a":2 , "b":5}