[英]Reading json file array 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"
]
}
键“urls”的值不是 JSONObject,它只是字符串数组。 你可以简单地这样做
for(int i=0; i < jsonArray.length(); i++){
data += jsonArray.getString(i);
}
更改data +=jsonObject;
到data +=String.valueOf(jsonObject)
。 您需要先将JSONObject
转换为String
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.