Reputation: 53
I'm currently trying to translate a String using Google Translate's "free" API.
The function I currenly have is the following:
static String sourceLang = "en";
static String targetLang = "de";
public static void translate(String msg) throws Exception {
msg = URLEncoder.encode(msg, "UTF-8");
URL url = new URL("http://translate.googleapis.com/translate_a/single?client=gtx&sl=" + sourceLang + "&tl="
+ targetLang + "&dt=t&q=" + msg + "&ie=UTF-8&oe=UTF-8");
URLConnection uc = url.openConnection();
uc.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
Which returns me, for example
[[["Das ist ein Satz","This is a sentence",,,3]],,"en"]
or
[[["Dies ist ein weiterer Satz mit einigen Symbolen \"$% \u0026 / () = º ~ ª ^","This is another sentence with a few symbols \"$%\u0026/()=º~ª^",,,3]],,"en"]
I've been looking into a few JSON parsing methods but I couldn't find a way to convert that to JSON then parse those 3 strings as three String or String[].
Any idea on how should it be properly done?
Thanks in advance!
Upvotes: 3
Views: 1609
Reputation: 1
here is simple code to parse the response.
var str = responseText.split("]]]]");
for (i=0; i<str.length-1; i++){
str[i] = str[i].split('","')[0].split('"')[1];
}
str.splice(-1);
str = str.join(" ");
Upvotes: 0
Reputation: 2050
This piece of code can do the trick:
Pattern p = Pattern.compile("\"([^\"]*)\"");
String line = "yourtext";
Matcher m = p.matcher(line);
while (m.find()) {
System.out.println("m.group(1)=" + m.group(1));
}
Upvotes: 1