BeginnerBro
BeginnerBro

Reputation: 195

Split String json

I have a String result=

{"fkcl":"5","fkdiv":["1","2","3","4","5"],"fkcl1":"3","fkdiv1":["1","2","3","4","5"]}

i want to split as

[{"fkcl":"5","fkdiv":["1","2","3","4","5"]}]
[{"fkcl1":"3","fkdiv":["1","2","3","4","5"]}]

Upvotes: 2

Views: 188

Answers (1)

ᴇʟᴇvᴀтᴇ
ᴇʟᴇvᴀтᴇ

Reputation: 12751

If you know the items always start with the string "fkcl", you might be able to use a regular expression to do this. E.g.

String json = "{\"fkcl\":\"5\",\"fkdiv\":[\"1\",\"2\",\"3\",\"4\",\"5\"],\"fkcl1\":\"3\",\"fkdiv1\":[\"1\",\"2\",\"3\",\"4\",\"5\"]}";

String output = json
    .replaceAll("\\{?(\"fkcl)", "\n[{$1")
    .replaceAll(",\n", "}]\n") + "]";

System.out.println(output);

Produces:

[{"fkcl":"5","fkdiv":["1","2","3","4","5"]}]
[{"fkcl1":"3","fkdiv1":["1","2","3","4","5"]}]

Otherwise parse the string with a JSON parser (e.g. GSON) and then iterate over the elements and split when desired.

Upvotes: 1

Related Questions