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),用"[]"包裹.
 

猜你喜欢

转载自essencer.iteye.com/blog/2063338