31

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.

Ahmed Alnabhan
  • 608
  • 1
  • 9
  • 13
TeaCupApp
  • 11,316
  • 18
  • 70
  • 150
  • you are getting a json string though right? You will need to define your variables too. Then you can do something like obj.translation to get the actual translation. I've never dealt with json in java before, so i really don't know how you would define that variable. Look at example 2 in the link you provided. While the string you have is nested though, but i really don't know how gson would parse that. – Matt May 21 '11 at 04:10
  • 1
    This question looks like a duplicate: http://stackoverflow.com/questions/1395551/convert-a-json-string-to-object-in-java?rq=1 – Anderson Green Apr 30 '13 at 14:40

3 Answers3

37

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.

Kevin
  • 24,871
  • 19
  • 102
  • 158
11

check this out Converting JSON to Java , i guess you can define a class as the object and pass that along. So, create some class and pass it along.

Data obj = gson.fromJson(json, Data.class);

class Data{
  public List<Data> getTranslation(){
     return translations;
  }
}

Try out something like that. You may need to experiment a little.

Community
  • 1
  • 1
Matt
  • 7,049
  • 7
  • 50
  • 77
  • Thanks for the answer however I am choosing second answer to be be more acceptable how ever your answer made my understanding more clear about Gson...cheers – TeaCupApp May 21 '11 at 10:45
  • @krio, thats fine, but i would go with kevins answer. gson looks to be more up to date and robust. – Matt May 21 '11 at 22:10
11

I usually like to use the plain org.json library

Use it as:

 // make sure the quotes are escaped
String str = "{\"data\":{\"translations\":[{\"translatedText\":\"Bonjour tout le monde\"}]}}";
 // the object data is inside a "global" JSONObject
data = new JSONObject(str).getJSONObject("data");
// get a JSONArray from inside an object
JSONArray translations = data.getJSONArray("translations");
// get the first JSONObject from the array
JSONObject text = translations.getJSONObject(0);
// get the String contained in the object -> logs Bonjour tout le monde
Log.d("***>Text", text.getString("translatedText"));

Maybe so much code is less clear than what I would have liked. This is the function as I would do it:

public String getTranslation(String json){  
  JSONObject data = new JSONObject(json).getJSONObject("data");
  return data.getJSONArray("translations").getJSONObject(0).getString("translatedText");
}
Aleadam
  • 40,203
  • 9
  • 86
  • 108
  • Nice to know a simple and new method! Thanks – TeaCupApp May 21 '11 at 10:43
  • 1
    That's super old school and nobody uses that library anymore in the real world. Pretty funny that it got marked as the right answer. – Kevin May 21 '11 at 16:12
  • 3
    @Kevin for such a simple task, I still find it the best approach. Just 2 LOCs and you get your result. You had to define 3 classes to get the same result with Gson. I won't deny its advantages in other situations, but I do not see any here.\ – Aleadam May 21 '11 at 17:04
  • That is true Aleadam, but what happens when you do need that extra stuff. Plus it makes it cleaner and easier to read, as well as to update. Java is all about OO programming no? – Matt May 21 '11 at 22:13
  • i use the same thing throughout my application. what is our opinion JSON parsing or OBJECT MODELLING – Shubham AgaRwal Sep 28 '16 at 22:27