Gson,JsonElement,Java中的字符串比较 [英] Gson, JsonElement, String comparison in Java
问题描述
我是使用Gson来处理几个JSON元素。在我的代码中的某处,我将JsonObject的JsonElements之一作为String,并将其与另一个String进行比较。据我可以看到他们都是平等的,但比较时,我总是得到错误。这是片段。
JsonArray arr;
JsonObject jsonobj;
JsonElement model_elem;
String STUPID_STRING =bla bla bla;
//以前我们初始化并填充arr,不管怎么样...我希望
jsonobj = arr.get(0).getAsJsonObject();
model_elem = jsonobj.get(coolname);
if(model_elem.toString()。equals(STUPID_STRING)){
...
它永远不会进入if语句。
arr在索引0处有元素,jsonobj有一个名称为coolname的字段,如果我println model_elem i get bla bla bla(与STUPID_STRING相同)。我已经尝试了equals()和compareTo()== 0。
我不知道这里发生了什么,有人知道吗? :-s。
提前致谢。
我相信您需要在GSON中使用 getAsString()
。 toString()
会加引号! 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.
I believe you need to use getAsString()
with GSON. toString()
will add quotes!
这篇关于Gson,JsonElement,Java中的字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!