Grichka Grichka - 4 months ago 10
Java Question

Split a string with a character between curly braces

I have following string :

{"attribute1":"value1","attribute2":"value2","attribute3":{"attribute3a":"value3a","attribute3b":"value3b"}},{"attribute1":"value1","attribute2":"value2","attribute3":{"attribute3a":"value3a","attribute3b":"value3b"}},{"attribute1":"value1","attribute2":"value2","attribute3":{"attribute3a":"value3a","attribute3b":"value3b"}}


I need to split this string on "," between "}}" and "{" and put each result in a tab.

The result I want is :

tab[0] : {"attribute1":"value1","attribute2":"value2","attribute3":{"attribute3a":"value3a","attribute3b":"value3b"}}
tab[1] : {"attribute1":"value1","attribute2":"value2","attribute3":{"attribute3a":"value3a","attribute3b":"value3b"}}
tab[2] : {"attribute1":"value1","attribute2":"value2","attribute3":{"attribute3a":"value3a","attribute3b":"value3b"}}


How can I do it?

Answer

Following code solves your problem

public class Test {

    public static void main(String args[]) {
        String input = "{\"attribute1\":\"value1\",\"attribute2\":\"value2\",\"attribute3\":{\"attribute3a\":\"value3a\",\"attribute3b\":\"value3b\"}},{\"attribute1\":\"value1\",\"attribute2\":\"value2\",\"attribute3\":{\"attribute3a\":\"value3a\",\"attribute3b\":\"value3b\"}},{\"attribute1\":\"value1\",\"attribute2\":\"value2\",\"attribute3\":{\"attribute3a\":\"value3a\",\"attribute3b\":\"value3b\"}}";
        String[] output = input.split("},");
        for(String s: output) {
            System.out.println(s+"}");
        }
    }

}

However, this is not an elegant way of doing it. You should try parsing your input using JSON libraries