GSON - Get JSON value from String

2020-02-02 11:45发布

问题:

I trying to parse the JSON String "{'test': '100.00'}" and 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 archieved?

回答1:

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


回答2:

Try

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

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



回答3:

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