GSON - Get JSON value from String

為{幸葍}努か 提交于 2019-12-17 17:53:15

问题


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



来源:https://stackoverflow.com/questions/20152710/gson-get-json-value-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!