Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

android - Converting json string to java object?

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.

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"}]}} 

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?

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;
 }
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT: You need your java Data class to be an exact model of the JSON. So your

{"data":{"translations":[{"translatedText":"Bonjour tout le monde"}]}} 

becomes:

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;
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...