Gson, JsonElement, String comparison in Java

余生颓废 提交于 2019-12-21 12:51:12

问题


Ok, I'm wondering this could be quite simple and stupid but after a while fighting with the situation I have no idea what is happening.

I'm using Gson to handle a few JSON elements. Somewhere in my code I get one of the JsonElements of a JsonObject as a String and I compare it against another String. As far as I can see both of them are equals but when comparing I always get false. Here is the snippet.

    JsonArray arr;
    JsonObject jsonobj;
    JsonElement model_elem;
    String STUPID_STRING = "bla bla bla";

    // Previously we initializes and fill arr, it doesn't matter how... I hope
    jsonobj = arr.get(0).getAsJsonObject();
    model_elem = jsonobj.get("coolname");
    if (model_elem.toString().equals(STUPID_STRING)) {
        ...

It never goes inside the if statement.

arr has element at index 0, jsonobj has a field with name "coolname" and if I println model_elem i get "bla bla bla" (the same as STUPID_STRING). I have tried equals() and also compareTo() == 0.

I cannot figure out what is happening here, does anyone knows? :-s.

Thanks in advance.


回答1:


I believe you need to use getAsString() with GSON. toString() will add quotes!



来源:https://stackoverflow.com/questions/16585351/gson-jsonelement-string-comparison-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!