Java 正则表达式为每个对象分割 JSON 字符串

标签 java json regex string split

我正在尝试从 JSON 文件读取对象的数据。我想让我的函数一个接一个地读取对象,而不是作为对象数组(这样我就可以处理每个对象的异常),所以我必须创建一个正则表达式,它会分割每个 JSON 对象的数据字符串。问题是,每个对象中都包含另一个对象,所以我无法使正则表达式在“},{”处分割,因为它将在内部花括号处分割,而不是在外部花括号处分割。下面是一个 JSON 文件示例:

{ 
  "vinForRepair" : "ABCDE123455432199",
  "dateOfRepair" : "17/08/2021",
  "mileage" : 100000,
  "items" : [ {
    "description" : "Water pump",
    "quantity" : 1,
    "price" : 120.0,
    "metric" : "UNIT
}, {         <---------This should be ignored
    "description" : "Motor oil",
    "quantity" : 1,
    "price" : 30.0,
    "metric" : "LITER"
  } ]
}, {         <---------This is where i want to split
  "vinForRepair" : "ABCDE123455432100",
  "dateOfRepair" : "15/08/2021",
  "mileage" : 250000,
  "items" : [ {
    "description" : "Break fluid",
    "quantity" : 1,
    "price" : 20.0,
    "metric" : "LITER"
  }, {       <---------This should be ignored
    "description" : "Tyre",
    "quantity" : 2,
    "price" : 80.0,
    "metric" : "UNIT"
 } ]
}

我尝试使用

String[] jsonObjectStringArray = jsonString.split("\\}, \\{\\n  \"vinForRepair\"");

在第一个对象属性处进行分割,但它不起作用。

我尝试使用 Jackson 来实现此目的,但它要么只读取一个对象,要么读取一组对象,正如我所说,我不想直接从文件读取数组。

最佳答案

您可以通过计算 json 的“深度”来代替使用正则表达式。当“{”出现时,深度增加,反之,当“}”出现时,深度减少。深度为零的大括号是您要拆分的位置。

private static List<String> split(String json) {
    List<String> result = new ArrayList<>();
    int depth = 0;
    int start = 0;
    for (int i = 0; i < json.length(); i++) {
        if (json.charAt(i) == '{') {
            if (depth == 0) {
                start = i;
            }
            depth++;
        }
        if (json.charAt(i) == '}') {
            depth--;
            if (depth == 0) {
                result.add(json.substring(start, i + 1));
            }
        }
    }
    return result;
}

您可以在此处运行该方法 https://ideone.com/vmnmCs

关于Java 正则表达式为每个对象分割 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68817833/

相关文章:

java - spring boot 找不到实体

Java 滚动面板调整大小

java - 如何删除列表中相似的命名字符串?

javascript - 如何向 bitstamp 发出 HTTP 请求?

java - java中解析json对象,找不到对象

java - 使用匹配器和正则表达式提取子字符串

java - 使用@Transient注解进行持久化存储

regex - 在正则表达式方面需要帮助

python - 使用 Python 正则表达式捕获占有者和前缀

javascript - 如何将多维列表转换为一维列表