Android JSON写入,解析

package com.example.he.toby.jsondemo;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


// TODO: 2016/2/23   jsonobject 轻量级的数据交换格式 ,json定义的基本单元,主要包含的就是一对(key/values)的值,使用{} 括起来的一组数据 ,{key ,values} ,{key,[数值1,数值2,数值3]}

// TODO: 2016/2/23  jsonarray 代表一种有序的数值,可以将对象的信息变化为字符串,所有的数据使用"[]"包裹,数值之间以","分隔,[数值1,数值2,数值3]

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private String data[] = {"www.baidu.com", "www.gigaset.com", "www.bbs.com"};
    private String nameData[] = new String[]{"xxx", "yyy", "zzzz", "mmmm"};
    private String companyTel = "1111111";

    private Button button;
    String str = "[{\"id\":1,\"name\":hjw\"}]";
    StringBuffer buffer = new StringBuffer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.textView = (TextView) findViewById(R.id.textview);
        this.button = (Button) findViewById(R.id.button);
        this.button.setOnClickListener(listener);


        JSONObject allData = new JSONObject();   // TODO: 2016/2/23 先建立最外边的alldata对象
        JSONArray sing = new JSONArray();         // TODO: 2016/2/23 建立新的jsonarray对象

        for (int x = 0; x < data.length; x++)                        // TODO: 2016/2/23 通过数组方式添加
        {
            JSONObject temp = new JSONObject();

            try {
                temp.put("myurl", data[x]);               // TODO: 2016/2/23 设置要保存的数据
                temp.put("second", nameData[x]);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            sing.put(temp);
            Log.e("main", "保存一个信息 ");
        }

        try {
            allData.put("urldata", sing);
            allData.put("telephone", companyTel);     // TODO: 2016/2/23  单独添加
            Log.e("main", "保存所有信息 ");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(getApplicationContext(), "有外置存储", Toast.LENGTH_SHORT).show();
            return;           // TODO: 2016/2/23 返回调用处
        }

        File file = new File(Environment.getExternalStorageDirectory().toString() + File.separator + "mldn" + File.separator + "json.txt");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        PrintStream out = null;       // TODO: 2016/2/23  打印流

        try {
            out = new PrintStream(new FileOutputStream(file));    //实例化打印流对象
            out.print(allData.toString());                    //输出数据
            Log.e("main", "write msg in json.txt");
            // str = allData.toString();
            textView.setText(allData.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();         // TODO: 2016/2/23 关闭打印流
            }
        }

    }

    // TODO: 2016/2/24  按键的监听
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.button:
                    Log.e("button", "解析得到的数据");
                    try {
                        List<Map<String, Object>> all = parseJson(str);
                        Iterator<Map<String, Object>> iterator = all.iterator();
                        while (iterator.hasNext()) {
                            Map<String, Object> map = iterator.next();
                            buffer.append("ID:" + map.get("id") + ",name: " + map.get("name"));
                            Log.e("json", "结果: " + buffer);
                            textView.setText(buffer);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };


    public List<Map<String, Object>> parseJson(String data) throws Exception {
        List<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
        JSONArray jsonArray = new JSONArray(data);
        for (int x = 0; x < jsonArray.length(); x++) {
            Map<String, Object> map = new HashMap<String, Object>();
            JSONObject jsonObject = jsonArray.getJSONObject(x);
            map.put("id", jsonObject.getString("id"));
            map.put("name", jsonObject.getString("name"));
            all.add(map);
        }

        return all;
    }


}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值