Unable to return JSON Object, within Object in Android app

前端 未结 3 485
有刺的猬
有刺的猬 2020-12-22 11:12

So I have an Android app I am working on that makes an API call to the server and returns JSON information. Now in my android app I can parse the JSON but only up until the

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-22 11:33

    I'm not sure which data from your JSON response, you are trying to extract. But I think this example with Google Translate API will help you out.

    JSON Response:

    "data": {
        "translations": [
            {
                "translatedText": "Hallo Welt",
                "detectedSourceLanguage": "en"
            }
        ]
    }
    

    If I want to get the translatedText, "Hallo Welt", I do it like this:

    public String parseJSONForTranslation(String jsonString) {
        try {
            JSONObject object = (JSONObject) new JSONTokener(jsonString).nextValue();
            return object.getJSONObject("data").getJSONArray("translations").
                    getJSONObject(0).getString("translatedText");
        }
        catch (JSONException e) {
            return null;
        }
    }
    

    So as you can see, if you want to further extract information by going into the next "level" of your JSON response, you use either getJSONObject or getJSONArray (depending on if it's an array or not) until you reach the "level" where the data you want to extract is at. And you only use getString when you are at that last "level". Hopefully, this can help you out.

提交回复
热议问题