fork(1) download
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class Main {
  5.  
  6. private static String json =
  7. "{ \n" +
  8. " \"vinForRepair\" : \"ABCDE123455432199\",\n" +
  9. " \"dateOfRepair\" : \"17/08/2021\",\n" +
  10. " \"mileage\" : 100000,\n" +
  11. " \"items\" : [ {\n" +
  12. " \"description\" : \"Water pump\",\n" +
  13. " \"quantity\" : 1,\n" +
  14. " \"price\" : 120.0,\n" +
  15. " \"metric\" : \"UNIT\n" +
  16. "}, { <---------This should be ignored\n" +
  17. " \"description\" : \"Motor oil\",\n" +
  18. " \"quantity\" : 1,\n" +
  19. " \"price\" : 30.0,\n" +
  20. " \"metric\" : \"LITER\"\n" +
  21. " } ]\n" +
  22. "}, { <---------This is where i want to split\n" +
  23. " \"vinForRepair\" : \"ABCDE123455432100\",\n" +
  24. " \"dateOfRepair\" : \"15/08/2021\",\n" +
  25. " \"mileage\" : 250000,\n" +
  26. " \"items\" : [ {\n" +
  27. " \"description\" : \"Break fluid\",\n" +
  28. " \"quantity\" : 1,\n" +
  29. " \"price\" : 20.0,\n" +
  30. " \"metric\" : \"LITER\"\n" +
  31. " }, { <---------This should be ignored\n" +
  32. " \"description\" : \"Tyre\",\n" +
  33. " \"quantity\" : 2,\n" +
  34. " \"price\" : 80.0,\n" +
  35. " \"metric\" : \"UNIT\"\n" +
  36. " } ]\n" +
  37. "}";
  38.  
  39. public static void main(String[] args) {
  40. List<String> jsons = split(json);
  41. System.out.println(jsons.size());
  42. jsons.forEach(it -> {
  43. System.out.println("-------");
  44. System.out.println(it);
  45. });
  46. }
  47.  
  48. private static List<String> split(String json) {
  49. List<String> result = new ArrayList<>();
  50. int depth = 0;
  51. int start = 0;
  52. for (int i = 0; i < json.length(); i++) {
  53. if (json.charAt(i) == '{') {
  54. if (depth == 0) {
  55. start = i;
  56. }
  57. depth++;
  58. }
  59. if (json.charAt(i) == '}') {
  60. depth--;
  61. if (depth == 0) {
  62. result.add(json.substring(start, i + 1));
  63. }
  64. }
  65. }
  66. return result;
  67. }
  68.  
  69. }
  70.  
Success #stdin #stdout 0.07s 49740KB
stdin
Standard input is empty
stdout
2
-------
{ 
  "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"
 } ]
}