小弧光的博客

公众号:小弧光黑板报

导航

JSON解析-android平台(转)

package org.lxh.demo;

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.os.Bundle;
import android.os.Environment;
import android.app.Activity;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String  data [] = new String [] {"www.mldnjava.cn","lixinghua",
                "bbs.mldn.cn"} ;
        JSONObject allData = new JSONObject() ;//最外面的节点对象
        JSONArray sing = new JSONArray() ; 
        for (int x = 0 ; x < data.length ; x++){
            JSONObject temp = new JSONObject() ; //每一个包装的数据都是JSONObject
            try {
                temp.put("myurl",data[x]);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            sing.put(temp) ; //保存多个JSONObject           
        }
        try {
            allData.put("urldata", sing) ;
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }   
        if(!Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED)){
            return ; 
        }
        File file = new File(Environment.getExternalStorageDirectory()
                +File.separator+"mldndata"+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) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(out != null){
                out.close() ;               
            }
        }
    }


}

 

posted on 2013-06-28 21:11  小弧光  阅读(174)  评论(0编辑  收藏  举报