Java GSON - 从字符串中获取 JSON 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20152710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:32:20  来源:igfitidea点击:

GSON - Get JSON value from String

javajsonparsinggson

提问by jan

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:

我试图解析 JSON 字符串 "{'test': '100.00'}" 并使用 GSON 库获取值:100.00。我的代码如下所示:

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?

我的结果看起来像这样:“100.00”,但如果没有引号,我只需要 100.00。如何存档?

采纳答案by Sanj

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

回答by dimoniy

Try

尝试

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

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

get(String) 方法返回JsonElement对象,然后您应该从中获取值。

回答by TimeTrax

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

如果你有一个字符串 => 在这种情况下,“result”被设置为第 3 行的一个字符串。 myJSONString 变量中的键“test”的值为 100.00 为了“DOUBLEFY”这个值 100.00,你调用Double 类中的 parseDouble 方法。这就是如何将 VALID 字符串 double 转换为 double Double.parseDouble(result); 将字符串“result”变成双精度