JSONObject和JSONArray
package com.jm.jason;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONObject allData = new JSONObject();
JSONArray jsonArr = new JSONArray();
String[] data = {"www.w1.com", "www.w2.com", "www.w3.com"};
for (int i = 0; i < data.length; i++) {
JSONObject temp = new JSONObject();
try {
temp.put("myurl", data[i]);
} catch (JSONException e) {
e.printStackTrace();
}
jsonArr.put(temp);
}
try {
// 保存所有数据
allData.put("urldata", jsonArr);
} catch (JSONException e) {
e.printStackTrace();
}
// SD卡是否已经mounted
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Log.i("TAG", "No SDCard!");
return;
}
// 定义SD卡上的文件
File file =
new File(Environment.getExternalStorageDirectory().toString()
+ File.separator + "url_data" + File.separator +"jason.txt");
// 建立文件所在路径
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
// 数据输出到文件
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream(file));
out.print(allData.toString());
Log.i("TAG", "Success!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
}<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
输出到文件:
可见:
1.JSONObject和JSONArray可以嵌套使用。
2.JSONObject中一个key含有多个value(即该key对应的value是个JSONArray),用"[]"包裹.
相关推荐
somebodyoneday 2020-06-15
83163452 2020-01-28
adonislu 2020-01-10
baijinswpu 2020-01-01
adonislu 2019-12-31
xufankang 2019-12-19
somebodyoneday 2019-12-07
somebodyoneday 2019-10-30
ZCMUCZX 2016-04-14
WebVincent 2020-07-21
fengchao000 2020-07-04
baijinswpu 2020-06-28
88483063 2020-06-28
fengchao000 2020-06-16
wujiajax 2020-06-14
somebodyoneday 2020-05-16
xx0cw 2020-05-16
newthon 2020-05-14