简体   繁体   中英

Java : Parsing a Json formated String to Java

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 .

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.

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. Eg

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM