GSON - Get JSON value from String

JavaJsonParsingGson

Java Problem Overview


I'm trying to parse the JSON String "{'test': '100.00'}" and in order to get the value: 100.00 with the GSON library. My code looks like this:

String myJSONString = "{'test': '100.00'}";
JsonObject jobj = new Gson().fromJson(myJSONString, JsonObject.class);

String result = jobj.get("test").toString();

System.out.println(result);

My result looks like this: "100.00", but I would need just 100.00 without the quotes. How can this be achieved?

Java Solutions


Solution 1 - Java

double result = jobj.get("test").getAsDouble();

Solution 2 - Java

Try

String result = jobj.get("test").getAsString();

get(String) method returns JsonElement object which you then should get the value from.

Solution 3 - Java

double getDoubleFromString = Double.parseDouble(result);

EDIT: per the comment below: Here is some explanation

if you ever have a string => in this case "result" was set to a string on line 3. The key "test" in the myJSONString variable has a value of 100.00 In order to "DOUBLEFY" this value of 100.00, you call the parseDouble method from the Double class. Thats is how to convert a VALID string double into a double Double.parseDouble(result); will turn the string "result' into a double

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjanView Question on Stackoverflow
Solution 1 - JavaSanjView Answer on Stackoverflow
Solution 2 - JavadimoniyView Answer on Stackoverflow
Solution 3 - JavaTimeTraxView Answer on Stackoverflow