Algirdas Butkus Algirdas Butkus -4 years ago 76
Java Question

Java GSON check data

I'm having trouble with gson:

For example I have this output from website:

[["connected"], ["user1":"Hello"], ["user2":"Hey"], ["disconnected"]]


But I want parse this JSON and output something like this:

connected
user1 says: Hello
user2 says: Hey
disconnected


I quicly wrote this code:

public static void PrintEvents(String id){
String response = Post.getResponse(Server()+"events?id="+id,"");
// response is [["connected"],["user1":"Hello"],["user2":"Hey"],["disconnected"]]

JsonElement parse = (new JsonParser()).parse(response); //found this in internet

int bound = ????????????; // Should be 4

for (int i=1;i<=bound;i++){
String data = ???????????;
if (data == "connected" || data == "disconnected") then {
System.out.println(data);
}else if(?????==2){// to check how many strings there is, if it's ["abc","def"] or ["abc"]
String data2 = ??????????????;
System.out.println(data+" says: "+data2);
}else{
//something else
}
};

}


What should I insert to these parts with question marks to make code work?

I cannot find any way to make it work...

Sorry for my bad English.

EDIT: Changed response to
[["connected"], ["user1","Hello"], ["user2","Hey"], ["disconnected"]]
. Earlier response was not valid JSON.

Answer Source
  1. The response that you have pasted is not a valid json. paste it in http://www.jsoneditoronline.org/ and see the error.

Please find the below code snippet:

public static void printEvents(String id) { String response = "[[\"connected\"] ,[\"user1:Hello\"],[\"user2:Hey\"],[\"disconnected\"]]";

    JsonElement parse = (new JsonParser()).parse(response); //found this in internet


    int bound = ((JsonArray)parse).size(); // Should be 4

    for (int i = 0; i < bound; i++) {
        String data = ((JsonArray)parse).get(0).getAsString();
        if (data.equals("connected") || data.equals("disconnected")) {
            System.out.println(data);
            continue;
        }
        String[] splittedData = data.split(":");
        if (splittedData.length
                == 2) {// to check how many strings there is, if it's ["abc","def"] or ["abc"]
            System.out.println(splittedData[0] + " says: " + splittedData[1]);
        }
        /*
        *else{
        * your else logic goes here
        * }
         *  */
    }

}

Couple of suggestions:

  1. If you are new to json world, use jackson instead of Gson.
  2. the response is not a good design. Slightly correct json:

{ "firstKey": "connected", "userResponses": [ { "user1": "hey" }, { "user2": "hi" } ], "lastKey": "disconnected" }

  1. Also try to define pojos , instead of working inline with json.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download