Wednesday, October 29, 2014

Working with JSON

Today I finally got the JSON code working! It does successfully translate most words into most of the languages, with some times it working with all four languages. The lack of fully translating properly, I've found, is ultimately due to their database not having all the necessary information.

The code I've used to get the JSON translated text is the following:

translation1 = "English: " + readJsonFromUrl("https://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=" + phrase + "&pretty=true").getJSONArray("tuc").getJSONObject(0).getJSONObject("phrase").get("text");

translation2 = "Spanish: " + readJsonFromUrl("https://glosbe.com/gapi/translate?from=eng&dest=spa&format=json&phrase=" + phrase + "&pretty=true").getJSONArray("tuc").getJSONObject(0).getJSONObject("phrase").get("text");

translation3 = "French: " + readJsonFromUrl("https://glosbe.com/gapi/translate?from=eng&dest=fra&format=json&phrase=" + phrase + "&pretty=true").getJSONArray("tuc").getJSONObject(0).getJSONObject("phrase").get("text");

translation4 = "German: " + readJsonFromUrl("https://glosbe.com/gapi/translate?from=eng&dest=deu&format=json&phrase=" + phrase + "&pretty=true").getJSONArray("tuc").getJSONObject(0).getJSONObject("phrase").get("text");

It was actually much more complicated than it seemed. I had to first read the JSON, from a method I created (named readJsonFromUrl), ultimately from the help of this StackOverflow post:


    public static JSONObject readJsonFromUrl(String url) throws Exception {
        InputStream inputStream = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String jsonText = read(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        }
        finally {
            inputStream.close();
        }
    }

From there, it gets an array known as "tuc", which, from glosbe, is the main array that stores the majority of the data. From there it's simply finding where the value was, I determined it to be the 1st object in tuc (index 0), then the object known as "phrase", and an inside object known as "text". This contained the translated word, which I used to add into a TextView and display to the user!

1 comment:

  1. I have a question about two of the imports from your StackOverflow link:

    import org.json.JSONException;
    import org.json.JSONObject;

    Where is org.json located? Does it have to be on your local machine, or are you loading these classes from the web? The Java classpath name space was supposed to be made up of URLs, so that objects could in principal be loaded from anywhere. I've only used Java in an academic setting, so I have never done this in practice. Is that what is happening here?

    ReplyDelete