转换JSON字符串到java对象? [英] Converting json string to java object?
问题描述
我一直在四处寻找相关的转换JSON字符串到Java对象的例子,但没有找到任何很好的例子。一个我发现真的很基本的一次,没有真正处理复杂的JSON字符串。
I have been looking around for examples related to converting JSON strings to Java object but haven't found any good examples. The one I found was really basic once and not really dealing with complex JSON strings.
我想提出一个应用程序翻译从英语到使用谷歌翻译API不同语言的字符串。在查询谷歌的反应是...... foolowing文本格式的JSON,
I am making an app to translate strings from english to different languages using google translate api. Google's response upon query is...foolowing text is formatted in JSON,
{"data":{"translations":[{"translatedText":"Bonjour tout le monde"}]}}
我approch至今使用GSON API,但是我通过实际卡住我应该怎么处理这个complecated结果,并创建Java对象?
my approch so far is using GSON API, however I am stuck by actually how should I manipulate this complecated result and create java object?
我的Java类是......。
My java class is.. .
import com.google.gson.Gson;
public class JSONConverter {
private String traslatedText;
/**
* Create an object of it self by manipulating json string
* @param json type: String
* @return String Translated text result from JSON responce
*/
public String getTranslation(String json){
Gson gson = new Gson();
JSONConverter obj = gson.fromJson(json, JSONConverter.class);
return obj.getTranslationForReturn();
}
/**
* Method return a translation to a private call
* @return String translation
*/
private String getTranslationForReturn(){
return this.traslatedText;
}
}
以上approch不工作,因为我没有得到卓悦兜售世界报上的回报,
Above approch is not working since I am not getting "Bonjour tout le monde" on return,
这将是非常高兴,如果有人可以延长我的理解。
it would be great pleasure if someone can extend my understanding.
推荐答案
编辑: 你需要你的Java数据类是JSON的精确模型。所以,你的
You need your java Data class to be an exact model of the JSON. So your
{"data":{"translations":[{"translatedText":"Bonjour tout le monde"}]}}
变成了:
class DataWrapper {
public Data data;
public static DataWrapper fromJson(String s) {
return new Gson().fromJson(s, DataWrapper.class);
}
public String toString() {
return new Gson().toJson(this);
}
}
class Data {
public List<Translation> translations;
}
class Translation {
public String translatedText;
}
由于对象模型变得更加复杂了org.json风格code改变方向朝不可读而GSON /杰克逊风格的对象映射仍然只是普通Java对象。
As the object model gets more complicated the org.json style code veers towards unreadable whereas the gson/jackson style object mapping is still just plain java objects.
这篇关于转换JSON字符串到java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!