0

I do a Action on Middle ware and if its success i get the Value as

String result = ["RESULT","DELETE","OK"]

And in Case if the Operation is Failed i get the resposne as

String result = ["RESULT","DELETE","ERROR"]

I need to know if the Operation is success Or Fail so for this i have done this

public class Test {

    public static void main(String args[]) {

        String result = "[\"RESULT\",\"DELETE\",\"ERROR\"]";

        if (!result.contains("ERROR")) {
            System.out.println("success");
        } else {
            System.out.println("Failed");
        }

    }

This is working fine , but not sure if this has any negative impact / or in cases the code may Fail .

Please suggest if there is a better approach .

1
  • 2
    Use a proper library to parse Json. E.g. Jackson. Commented Feb 19, 2013 at 13:33

3 Answers 3

3

Your code can fail if, for instance, you get a success message containing ERROR (not likely, but can happen).

You should use a library to parse the result into a List/Array, look here on StackOverflow for a ton of solutions for parsing Json Strings to Objects in Java (Jackson is a library to do this, for instance).

You should also validate against a pre-set number of hypothesis, for instance, creating an enum for the possible result types, and checking if it's one of them.

Sign up to request clarification or add additional context in comments.

Comments

0

I would suggest to use object presentation instead of array here:

{
 "RESULT": {
   "operation": "DELETE",
   "status" : "ERROR"
 }
}

There is you can find a lot of tools to parse JSON in Java objects: http://www.json.org/

In other case it will be hard to extend set of codes. E.g.

String result = "[\"RESULT\",\"CREATE\",\"USER\", \"LOGIN\", \"ERROR\", \"SUCCESS\"]";

Was there error? or user with login ERROR was successfully created?

Comments

-1
String[] result = {"RESULT","DELETE","OK"};
    if(Arrays.asList(result).contains("OK"))
        System.out.println("Ok");

Try Arrays.asList() method to check given arrays contains that element or not.

1 Comment

Type mismatch: cannot convert from String to String[]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.