public class MainActivity extends Activity {
private TextView tv;
private String text;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView);
// 获取assets中测试json文本
AssetManager assetManager = getAssets();
try {
InputStream inputStream = assetManager.open("testjson.txt");
text = read(inputStream);
try {
JSONArray jArray = new JSONArray(text);
for (int i=0; i<jArray.length(); i++){
JSONObject item = jArray.getJSONObject(i);
Log.d("-----------每一条JSON数据-------->>", "姓名:" + item.optString("name")
+ "年龄:" + item.optString("age") + "出生日期:" + item.optString("born"));
}
} catch (JSONException e) {
e.printStackTrace();
}
// tv是TextView显示json串
tv.setText(text);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 进行IO流读写
* @param inputStream txt文件流
*/
private String read(InputStream inputStream) {
try {
ByteArrayOutputStream oStream = new ByteArrayOutputStream();
int length;
while ((length = inputStream.read()) != -1) {
oStream.write(length);
}
return oStream.toString();
} catch (IOException e) {
return "读写失败";
}
}
private TextView tv;
private String text;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView);
// 获取assets中测试json文本
AssetManager assetManager = getAssets();
try {
InputStream inputStream = assetManager.open("testjson.txt");
text = read(inputStream);
try {
JSONArray jArray = new JSONArray(text);
for (int i=0; i<jArray.length(); i++){
JSONObject item = jArray.getJSONObject(i);
Log.d("-----------每一条JSON数据-------->>", "姓名:" + item.optString("name")
+ "年龄:" + item.optString("age") + "出生日期:" + item.optString("born"));
}
} catch (JSONException e) {
e.printStackTrace();
}
// tv是TextView显示json串
tv.setText(text);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 进行IO流读写
* @param inputStream txt文件流
*/
private String read(InputStream inputStream) {
try {
ByteArrayOutputStream oStream = new ByteArrayOutputStream();
int length;
while ((length = inputStream.read()) != -1) {
oStream.write(length);
}
return oStream.toString();
} catch (IOException e) {
return "读写失败";
}
}
}
txt
[{"name":"战斗小鸡","age":"13","born":"1955-6-9"},{"name":"战斗小鸭","age":"19","born":"1999-9-9"}
,{"name":"战斗小猪","age":"20","born":"1985-1-24"},{"name":"战斗小兔","age":"18","born":"1981-3-10"}
,{"name":"战斗小熊","age":"22","born":"1995-7-16"},{"name":"战斗小明","age":"26","born":"2000-8-14"}]