4

I have following JSON response:

enter image description here

It means server had exception.

How can I parse any JSON string that I got from server for existence of exception without any third-parties?

Once I determine that JSON contains exception I need to fetch code/message/status values.

ybonda
  • 1,546
  • 25
  • 38

2 Answers2

4

Based on Crazy Dino comment here this is the correct solution for my problem:

        String json = str1;  // sample json string
        Pattern codePattern = Pattern.compile("\"code\"\\s*:\\s*\"([^,]*)\",");
        Pattern messagePattern = Pattern.compile("\"message\"\\s*:\\s*\"([^,]*)\",");
        Pattern statusPattern = Pattern.compile("\"status\"\\s*:\\s*\"(FAILURE)\"");

        Matcher code_matcher = codePattern.matcher(json);
        Matcher message_matcher = messagePattern.matcher(json);
        Matcher status_matcher = statusPattern.matcher(json);

        if (code_matcher.find() && message_matcher.find() && status_matcher.find()) {

            System.out.println("\nException found!");

            System.out.println("\n" + code_matcher.group(1));
            System.out.println("\n" + message_matcher.group(1));
            System.out.println("\n" + status_matcher.group(1));
        }

And the output:

Exception found!

INVALID_PARAMETER_VALUE

Invalid value for parameter: language_code

FAILURE
ybonda
  • 1,546
  • 25
  • 38
3

Would Regex be allowed (part of the core Java API)? You should be able to use it to extract String from bigger strings.

Pattern codePattern = Pattern.compile("\"code\": \".*\"");
        Matcher matcher = codePattern.matcher(json);

        if (matcher.find()) {
            System.out.println("\ncode: " + matcher.group(0));
        }

(Rinse and repeat for message and status)

Please note i'm away from my IDE so was unable to test the actual REGEX side of this, however the pattern/matcher code should be sound (was based off https://stackoverflow.com/a/4662265/1600472).

Community
  • 1
  • 1
Crazy Dino
  • 808
  • 1
  • 8
  • 20