英文:
Put Json In to Array using Gson
问题
String command = IInfo.CMD + "&lang=" + combo_from.getSelectedItem()
+ "-" + combo_to.getSelectedItem() + "&text=" + txt_word.getText();
System.out.println(command);
System.out.println("btn pushed");
try (Reader reader = new InputStreamReader(
Runtime.getRuntime().exec(command).getInputStream()
)) {
JsonElement json = new JsonParser().parse(reader);
System.out.println(json);
} catch (IOException e) {
e.printStackTrace();
}
英文:
Hello So I am writing an online translator using Yandex free tool .
I have this program that when user clicked on btn_translate I get the from and to languages from the comboBoxes then I get the text from the text label . Sending it to the server via the curl command.
keep in mind that i'm a beginner in this field so my code can have tons of problems ...
Here is the url sample:
>
https://translate.yandex.net/api/v1.5/tr.json/translate?key=API-KEY&lang=en-fa&text=hi
and here is the Json returned by the yandex:
> {"code":200,"lang":"en-fa","text":["سلام"]}
So Here is my question:
I want to access the 3rd item in this Json as you can see it is "text" how should i do that ?
i am using Gson and i don't know how to put this Json i'm receiving in to an array which is like this :
Array[0] = 200 ( Code )
Array[1] = "en-fa" ( Lang )
Array[2] = "سلام" ( text )
and here is my code ( btn pushed part ) :
String command = IInfo.CMD +"&lang="+combo_from.getSelectedItem()
+"-"+combo_to.getSelectedItem()+"&text="+txt_word.getText();
System.out.println(command);
System.out.println("btn pushed");
try(Reader reader = new InputStreamReader(
Runtime.getRuntime().exec(command).getInputStream()
)){
JsonElement json = new JsonParser().parse(reader);
System.out.println(json);
} catch (IOException e)
{
e.printStackTrace();
}
and if you can explain to me how my try is working it would be awesome !
thanks.
答案1
得分: 1
使用稍微修改后的响应读取方式,您可以按照以下方式进行操作:
JsonObject jsonObj = new JsonParser().parse(reader).getAsJsonObject();
jsonObj.get("code") ==> 200;
jsonObj.get("lang") ==> "en-fa";
jsonObj.get("text").getAsString() ==> "سلام";
英文:
With little changes to how you read the response you can do it like below:
JsonObject jsonObj = new JsonParser().parse(reader).getAsJsonObject()
jsonObj.get("code") ==> 200
jsonObj.get("lang") ==> "en-fa"
jsonObj.get("text").getAsString() ==> "سلام"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论