Split a simple JSON structure using a regular expression

后端 未结 1 730
忘掉有多难
忘掉有多难 2021-01-02 10:19

I\'ve never used a regex before and I am looking to split up a file that has one or more JSON objects, the JSON objects are not separated by a comma. So I need to split them

相关标签:
1条回答
  • 2021-01-02 10:37

    If your objects aren't more complex than what you show, you may use lookarounds like this :

    String[] strs = str.split("(?<=\\})(?=\\{)");
    

    Exemple :

    String str = "{id:\"123\",name:\"myName\"}{id:\"456\",name:\"yetanotherName\"}{id:\"456\",name:\"anotherName\"}";
    String[] strs = str.split("(?<=\\})(?=\\{)");
    for (String s : strs) {
        System.out.println(s);          
    }
    

    prints

    {id:"123",name:"myName"}
    {id:"456",name:"anotherName"}
    {id:"456",name:"yetanotherName"}
    

    If your objects are more complex, a regex wouldn't probably work and you would have to parse your string.

    0 讨论(0)
提交回复
热议问题