Java GSON检查数据

时间:2017-06-12 19:28:20

标签: java gson

我在使用gson时遇到了麻烦:

例如我从网站获得此输出:

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

但我想解析这个JSON并输出如下内容:

connected
user1 says: Hello
user2 says: Hey
disconnected

我写了这段代码:

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
         }
    };

}

我应该用问号插入这些部分以使代码有效?

我找不到任何办法让它发挥作用......

抱歉我的英语不好。

编辑:更改了对[["connected"], ["user1","Hello"], ["user2","Hey"], ["disconnected"]]的回复。早期的回复是无效的JSON。

2 个答案:

答案 0 :(得分:0)

您需要定义一个单独的类:

class MyClass{
String name;
String value;
}

然后:

List<MyClass> myclasses = new Gson().fromJson(response, new TypeToken<List<MyClass>>(){}.getType());

然后

for(MyClass myclass: myclasses){
...
}

答案 1 :(得分:0)

  1. 您粘贴的响应不是有效的json。将其粘贴到http://www.jsoneditoronline.org/并查看错误。
  2. 请找到以下代码段:

    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
            * }
             *  */
        }
    
    }
    

    一些建议:

    1. 如果您是json world的新手,请使用jackson代替Gson。
    2. 响应不是一个好的设计。略微纠正json:
    3. {   “firstKey”:“连接”,   “userResponses”:[     {       “user1”:“嘿”     },     {       “user2”:“hi”     }   ]   “lastKey”:“断开连接” }

      1. 还尝试定义pojos,而不是与json一起内联。