[Java] How would I output the following JSON?

RastaLulz

fight teh power
Staff member
May 3, 2010
3,935
3,936
I'm trying to register a user via a XenForo API add-on, which returns information in the form of JSON. I need to be able to check if any errors are in the JSON response, and if they are, go through each one, and send the message to the player; meaning I'd have to loop through "errors".

Here's what the JSON file would look like:
Code:
{
   "errors":{
      "email":"Email addresses must be unique. The specified email address is already in use.",
      "username":"Usernames must be unique. The specified username is already in use."
   },
   "system_info":{
      "visitor_id":0,
      "time":1398536381
   }
}

Obviously what the API returns is dynamic, so you won't always have an error for email or username, and could possibly have an error for something else. On top of that, if it's successful, it'll send the newly created users information, as oppose to any errors. Any help would be appreciated.
 
Solution
If anyone is having a similar issue in the future, here is how I did it using "json-simple".
Code:
            JSONParser parser = new JSONParser();

            JSONObject jsonObject = (JSONObject) parser.parse(responseBody);

            if(jsonObject.get("errors") == null) {

                MessageManager.playerActionMessage("Register", "You have successfully registered.", ChatColor.AQUA, ChatColor.GREEN, player);

            }else{

                JSONObject errorsObject = (JSONObject) jsonObject.get("errors");

                Set<String> errorKeys = errorsObject.keySet();

                for(String errorKey : errorKeys) {

                    String errorMessage = errorsObject.get(errorKey).toString()...

RastaLulz

fight teh power
Staff member
May 3, 2010
3,935
3,936
If anyone is having a similar issue in the future, here is how I did it using "json-simple".
Code:
            JSONParser parser = new JSONParser();

            JSONObject jsonObject = (JSONObject) parser.parse(responseBody);

            if(jsonObject.get("errors") == null) {

                MessageManager.playerActionMessage("Register", "You have successfully registered.", ChatColor.AQUA, ChatColor.GREEN, player);

            }else{

                JSONObject errorsObject = (JSONObject) jsonObject.get("errors");

                Set<String> errorKeys = errorsObject.keySet();

                for(String errorKey : errorKeys) {

                    String errorMessage = errorsObject.get(errorKey).toString();

                    MessageManager.playerActionMessage("Register", errorMessage, ChatColor.AQUA, ChatColor.RED, player);

                }

            }
 
Solution

Users who are viewing this thread

Top