使用 Gson for Java 解析 JSON [英] JSON parsing using Gson for Java
本文介绍了使用 Gson for Java 解析 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从 String
类型的 JSON 中解析数据.我正在使用 Google Gson.
I would like to parse data from JSON which is of type String
.
I am using Google Gson.
我有:
jsonLine = "
{
"data": {
"translations": [
{
"translatedText": "Hello world"
}
]
}
}
";
我的班级是:
public class JsonParsing{
public void parse(String jsonLine) {
// there I would like to get String "Hello world"
}
}
推荐答案
这是一个简单的代码,我避免了所有检查,但这是主要思想.
This is simple code to do it, I avoided all checks but this is the main idea.
public String parse(String jsonLine) {
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("data");
JsonArray jarray = jobject.getAsJsonArray("translations");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("translatedText").getAsString();
return result;
}
为了使使用更通用 - 你会发现 Gson 的 javadocs 非常清楚而且很有帮助.
To make the use more generic - you will find that Gson's javadocs are pretty clear and helpful.
这篇关于使用 Gson for Java 解析 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文