使用 gson 和 GsonBuilder() 解析 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13307222/
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
parse JSON with gson and GsonBuilder()
提问by senzacionale
String jsons = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";
This is my json string. How can i parse it to GsonBuilder() that i will get object back? I try few thinks but none works.
这是我的 json 字符串。我如何将它解析为 GsonBuilder() 以便我取回对象?我尝试很少思考,但没有任何效果。
I also read https://sites.google.com/site/gson/gson-user-guide
回答by Ilya
public class YourObject {
private String appname;
private String Version;
private String UUID;
private String WWXY;
private String ABCD;
private String YUDE;
//getters/setters
}
parse to Object
解析为对象
YourObject parsed = new Gson().fromJson(jsons, YourObject.class);
or
或者
YourObject parsed = new GsonBuilder().create().fromJson(jsons, YourObject.class);
minor test
次要测试
String jsons = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";
YourObject parsed = new Gson().fromJson(jsons, YourObject.class);
works well
效果很好
EDIT
in this case use JsonParser
在这种情况下使用编辑JsonParser
JsonObject object = new JsonParser().parse(jsons).getAsJsonObject();
object.get("appname"); // application
object.get("Version"); // 0.1.0
回答by Anthony Grist
JSON uses double quotes ("), not single ones, for strings so the JSON you have there is invalid. That's likely the cause of any issues you're having converting it to an object.
JSON"对字符串使用双引号 ( ),而不是单引号,因此您拥有的 JSON 无效。这可能是您将其转换为对象时出现任何问题的原因。

