如何在json字符串java中的数字之间给出一个空格?

时间:2015-11-11 13:19:28

标签: java json regex string gson

在我的下面代码中,我使用gson创建一个json字符串:

private String generateData(Map<String, Map<Integer, Set<Integer>>> nodeTable, int i) {
    JsonObject jsonObject = new JsonObject();

    Set<Integer> pp = nodeTable.get("TEXTER").get(i);
    Set<Integer> sp = nodeTable.get("PETER").get(i);

    // my above pp and sp variables shows correct values with one space between numbers.

    jsonObject.addProperty("description", "Hello. World");
    jsonObject.add("data1", gson.toJsonTree(pp));
    jsonObject.add("data2", gson.toJsonTree(sp));

    System.out.println(jsonObject.toString());

    return jsonObject.toString();
}

当我得到我的json字符串时,我就这样得到它。正如你在逗号后看到的,一切都是彼此相邻而没有任何空格。我不想那样。

{"description":"Hello. World.","data1":[0,273,546,819,1092,559],"data2":[816,1644,1368,276]}

我希望data1和data2变量中的数字之间有一个空格,如下所示:

{"description":"Hello. World.","data1":[0, 273, 546, 819, 1092, 559],"data2":[816, 1644, 1368, 276]}

使用gson或其他方式可以做到这一点吗?

2 个答案:

答案 0 :(得分:1)

这似乎是一个具有潜在错误的美容请求。最简单的方法可能是使用正则表达式:

jsonString = jsonString
    .replaceAll("(\\d),(\\d)", "$1, $2")
    .replaceAll("(\\d),(\\d)", "$1, $2")

上面的行只是捕获任何数字+逗号+数字序列,并在两个捕获和恢复的数字之间添加一个空格。由于java只捕获一次匹配,因此不允许交叉,我们在这里做了两次。

替代方案不是那么严格,但不需要双重替换:

jsonString = jsonString.replaceAll(",(\\d)", ", $1")

这里的bug可能是这适用于整个JSON字符串,而不仅仅是编码集。

正确的方法是为GSON使用自定义格式化器。

顺便说一句,地图地图为课堂哭泣。

答案 1 :(得分:1)

使用以下方法获取空间的最简单方法

For 1:
jsonObject.add("data1", gson.toJsonTree(addSpaces(pp)));
jsonObject.add("data2", gson.toJsonTree(addSpaces(sp)))

For 2: 
String string = addSpaceByRegEx(jsonObject.toString());

在您的课程中添加以下方法:

//1. if you need String value based spaces in json string
public Set<String> addSpaces(Set<Integer> integers) {
    Set<String> strings = new HashSet<>();
    for (Integer i : integers) {
        strings.add(i.toString() + " ");
    }
    return strings;
}

//2. if you need space as in integer value in json string as your example
//This method add space by using regex 
//Tested for String s = "{'description':'Hello. World.','data1':[0,273,546,819,1092,559],'data2':[816,1644,1368,276]}";
//In you example just replace following line
//System.out.println(jsonObject.toString()); by System.out.println(addSpaceByRegEx(jsonObject.toString()));
//See result, i think it work
public String addSpaceByRegEx(String jsonString) {
    Pattern pattern = Pattern.compile(",[0-9]");
    Matcher matcher = pattern.matcher(jsonString);
    StringBuilder sb = new StringBuilder();
    int prevIndex = 0;
    while (matcher.find()) {
        int startIndex = matcher.start();
        int endIndex = matcher.end();
        sb.append(jsonString.substring(prevIndex, startIndex + 1)).append(" ").append(jsonString.substring(startIndex + 1, endIndex));
        prevIndex = endIndex;
    }
    sb.append(jsonString.substring(prevIndex, jsonString.length()));
    return sb.toString();
}