76

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?

Philzen
  • 3,945
  • 30
  • 46
jan
  • 3,923
  • 9
  • 38
  • 78

3 Answers3

88
double result = jobj.get("test").getAsDouble();
Sanj
  • 3,879
  • 2
  • 23
  • 26
20

Try

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

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

dimoniy
  • 5,820
  • 2
  • 24
  • 22
1
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

Timetrax
  • 1,373
  • 13
  • 15
  • 5
    Can you elaborate on your answer a bit? – Athena Aug 28 '18 at 19:12
  • 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 – Timetrax Aug 29 '18 at 20:27