Sample code: Translate natural language with the Watson Language Translator service

Use the Java API for the Watson language translator service

Comments

Interactive code: When you see Run at the top of a code sample, you can run the code, check the results, make changes, and run it again. When you see Deploy, you can deploy the code into the developerWorks Bluemix account.

About this code

This code shows you how to use the Java API for the Watson language translator service. Given some text, a source language, and a target language, Watson translates that text and returns one or more translations to you.

The code has three basic sections:

  1. Default values for the parameters. These are always used by the public static void main(String[] args) method. If the call to public static JsonObject main(JsonObject args) has no parameters or the wrong number of parameters, the default values are also used there.
  2. The public static void main(String[] args) method. This uses a JsonParser to convert the default parameters into a JSON object, then it calls...
  3. ...The public static JsonObject main(JsonObject args) method. This is the action the IBM Cloud Functions platform invokes once the code is deployed.
Show result

Lines 55-66 illustrate the Java API for the service. The Watson SDK wraps the JSON returned by the service as a set of objects that are easy to work with in Java. Notice that it is possible for a translation to return multiple results. If Watson returns only one result, that's the only one the code displays. See the overview of the Language Translator service or the github repo for the Java API for more information.

Try changing the text or the languages to see what happens.

Using this code once deployed

To use this code once you've deployed it, you must create an instance of the Watson Language Translator service:

To invoke the code, pass a JSON structure that matches the data object as shown above with the following changes:

  1. The username, password, and endpoint fields must be filled in with the credentials for your Language Translator service instance.
  2. The skip_authentication field must be false.

For more information, see the developerWorks tutorial Invoking actions on the IBM Cloud Functions platform.


Related topics


Comments

Sign in or register to add and subscribe to comments.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Cognitive computing, Java development
ArticleID=1047460
ArticleTitle=Sample code: Translate natural language with the Watson Language Translator service
publish-date=08182017