将json字符串转换为java对象? [英] Converting json string to java object?

查看:38
本文介绍了将json字符串转换为java对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找与将 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.

我正在制作一个应用程序,使用 google translate 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"}]}} 

到目前为止,我的方法是使用 GSON API,但是,实际上我应该如何操作这个复杂的结果并创建 java 对象?

my approach so far is using GSON API, however, I am stuck by actually how should I manipulate this complicated 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;
 }
}

上述方法不起作用,因为我在返回时没有收到Bonjour tout le monde",

Above approach is not working since I am not getting "Bonjour tout le monde" on return,

如果有人能扩展我的理解,我会很高兴.

it would be a great pleasure if someone can extend my understanding.

推荐答案

您需要 Java Data 类作为 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 风格的代码变得不可读,而 gson/jackson 风格的对象映射仍然只是普通的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆