读取json文件数组Java Android Studio

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"
  ]
}
shenlong1943 回答:读取json文件数组Java Android Studio

键“ urls”的值不是JSONObject,而只是String的数组。您可以像这样

    for(int i=0; i < jsonArray.length(); i++){
       data += jsonArray.getString(i);
    }
,

data +=jsonObject;更改为data +=String.valueOf(jsonObject)。您需要先将JSONObject转换为String

本文链接:https://www.f2er.com/3148329.html

大家都在问