在AndroidManifest.xml中配置权限:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.li.json"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MyJSONDemo"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
在MyJSONDemo.java程序中
package com.li.json;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
public class MyJSONDemo extends Activity {
private String nameData[] = new String[]{"李叶文","河池学院","HCXY"};
private int ageData[] = new int[]{24,6,10};
private boolean isNarraiedData[] = new boolean[]{false,true,false};
private double salaryData[] = new double[]{3500,5000,6000};
private Date birthdayData[] = new Date[]{new Date(),new Date(),
new Date()};
private String companyName = "广西河池学院";
private String companyAddr = "宜州龙江河畔";
private String companyTel = "0778-01010101";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
JSONObject allData = new JSONObject(); //建立最外面的节点对象
JSONArray sing = new JSONArray(); //定义操作数组
for(int x = 0;x < this.nameData.length; x++){ //将数组内容配置到相应的节点
JSONObject temp = new JSONObject(); //每一个包装的数据都是JSONObject
try {
temp.put("name", this.nameData[x]);
temp.put("age", this.ageData[x]);
temp.put("married", this.salaryData[x]);
temp.put("birthday", this.birthdayData[x]);
} catch (JSONException e) {
e.printStackTrace();
}
sing.put(temp); //保存多个JSONObject
}
try {
allData.put("persondtata", sing);
allData.put("company", this.companyName);
allData.put("address", this.companyAddr);
allData.put("telephone", this.companyTel);
} catch (JSONException e) {
e.printStackTrace();
}
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) { // 不存在不操作
return; // 返回到程序的被调用处
}
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "liyewen" + File.separator
+ "json.txt"); // 要输出文件的路径
if (!file.getParentFile().exists()) { // 文件不存在
file.getParentFile().mkdirs() ; // 创建文件夹
}
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream(file));
out.print(allData.toString()); //将数据变为字符串后保存
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally{
if(out != null){
out.close(); //关闭输出
}
}
}
}