fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. String[] inputs = {
  13. "String Notify : {\"id\": \"1234\", \"transactionId\": \"TR-001\", \"timestamp\": \"1575445871\"} with result success",
  14. "String Notify : {\"id\": \"1234\", \"transaction\": { \"id\" : \"TR-002\" }, \"timestamp\": \"1575445871\"} with result success",
  15. "String Notify : {\"id\": \"1234\", \"transaction\": { \"id\" : \"TR-002\" }, \"timestamp\": \"1575445871\" which should fail"
  16. };
  17. for (String input : inputs) {
  18. System.out.println("Parsing " + input);
  19. System.out.println(extractJson(input));
  20. }
  21. }
  22.  
  23. public static String extractJson(String input) {
  24. int depth=0;
  25. StringBuilder currentJsonString=new StringBuilder();
  26. boolean containsValidJson = false;
  27. for (char c: input.toCharArray()) {
  28. if (c == '{') { depth++; }
  29. else if (c == '}' && depth > 0) { // if depth==0, the } isn't part of a JSON object
  30. depth--;
  31. if (depth == 0) {
  32. currentJsonString.append(c);
  33. containsValidJson = true;
  34. break;
  35. }
  36. }
  37. if (depth > 0) { currentJsonString.append(c); }
  38. }
  39. if (containsValidJson) {
  40. return currentJsonString.toString();
  41. } else {
  42. return null; // or better, throw exception
  43. }
  44. }
  45. }
Success #stdin #stdout 0.1s 35980KB
stdin
Standard input is empty
stdout
Parsing String Notify : {"id": "1234", "transactionId": "TR-001", "timestamp": "1575445871"} with result success
{"id": "1234", "transactionId": "TR-001", "timestamp": "1575445871"}
Parsing String Notify : {"id": "1234", "transaction": { "id" : "TR-002" }, "timestamp": "1575445871"} with result success
{"id": "1234", "transaction": { "id" : "TR-002" }, "timestamp": "1575445871"}
Parsing String Notify : {"id": "1234", "transaction": { "id" : "TR-002" }, "timestamp": "1575445871" which should fail
null