Чтение массива файлов json Java Android studio - PullRequest
0 голосов
/ 07 ноября 2019
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView output = (TextView) findViewById(R.id.textView1);
        String strJson=null;
        String data = "";
        try {
            InputStream inputStream = getAssets().open("urls.json");
            int size = inputStream.available();
            byte [] buffer = new byte[size];
            inputStream.read(buffer);
            inputStream.close();
            strJson = new String(buffer,"UTF-8");
            // Create the root JSONObject from the JSON string.
            JSONObject  jsonRootObject = new JSONObject(strJson);

            //Get the instance of JSONArray that contains JSONObjects
            JSONArray jsonArray = jsonRootObject.optJSONArray("urls");

            //Iterate the jsonArray and print the info of JSONObjects
            for(int i=0; i < jsonArray.length(); i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                data +=jsonObject;
            }
            output.setText(data);
        } catch (JSONException | IOException e) {e.printStackTrace();}
    }
}

Я получил 0 ошибок. Но в textview ничего не отображается. мой файл json выглядит как

{
  "urls": 
  [
    "a",
    "b",
    "c",
    "d",
    "e"
  ]
}

Ответы [ 2 ]

0 голосов
/ 07 ноября 2019

изменить data +=jsonObject; на data +=String.valueOf(jsonObject). вам нужно сначала конвертировать JSONObject в String.

0 голосов
/ 07 ноября 2019

Значение ключа "urls" не является JSONObject, это просто массив String. Вы можете просто сделать это

    for(int i=0; i < jsonArray.length(); i++){
       data += jsonArray.getString(i);
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...