使用Gson将Json放入数组中

huangapple go评论80阅读模式
英文:

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()  ==> "سلام" 

huangapple
  • 本文由 发表于 2020年5月5日 20:42:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/61613422.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定