Reputation: 32331
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 .
Upvotes: 0
Views: 113
Reputation: 885
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?
Upvotes: 0
Reputation: 12843
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.
Upvotes: -1
Reputation: 15990
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.
Upvotes: 3