Gson, JsonElement, string comparison in Java

Well, I'm curious that this can be pretty simple and stupid, but after a while, when I struggle with the situation, I have no idea what is going on.

I use Gson to handle multiple JSON elements. Somewhere in my code, I get one of the JsonElements JsonObject as a String, and I compare it to another string. As far as I can see, they are both equal, but when compared, I always become false. Here is a 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 enters an if statement.

arr has an element with index 0, jsonobj has a field called "coolname", and if I have println model_elem, I get "bla bla bla" (same as STUPID_STRING). I tried equals () as well as compareTo () == 0.

I can’t understand what’s going on here, does anyone know?:. -s

Thanks in advance.

+6
source share
1 answer

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

+13
source

Source: https://habr.com/ru/post/945147/