JSON解析

来源:互联网 发布:ue软件查看内码 编辑:程序博客网 时间:2024/06/08 01:00
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

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

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import com.example.day14json.bean.People;

public class MainActivity extends Activity {

    List<People> list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        String jsonStr = getJsonFromAssets("json.txt");
        Log.i("================", jsonStr);
        
        list = new ArrayList<People>();
        
        //使用读取出来的json字符串进行  json解析
        parseJson(jsonStr);
        
        Log.i("=======================", list.toString());
    }

    private void parseJson(String jsonStr) {
        try {
            JSONObject object = new JSONObject(jsonStr);
            JSONArray peopleArray = object.optJSONArray("people");
            for (int i = 0; i < peopleArray.length(); i++) {
                //从数组中过去数据 使用的方法 要根据数组中的数据格式来确定
                //如果数组中是Json对象结构 使用optJSONObject(index)
                //如果数组中是String结构 使用optString(index)
                JSONObject peopleObject = peopleArray.optJSONObject(i);
                String email = peopleObject.optString("email");
                String firstName = peopleObject.optString("firstName");
                String lastName = peopleObject.optString("lastName");
                
                People people = new People(email, firstName, lastName);
                list.add(people);

            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private String getJsonFromAssets(String fileName) {
        String jsonStr = "";
        //从assets文件夹中   把json.txt中的json字符串读取到内存中
        try {
            InputStream is = getAssets().open(fileName);
            //把输入流中的内容读到内存中
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            //如果数据输出到了byte数组中  我们可以使用new String("byte数组")转成字符串
            //把数据流中的数据  放入到 输出流中
            int len = -1;
            byte[] buff = new byte[1024];
            while((len = is.read(buff)) != -1){
                bos.write(buff, 0, len);
            }
            //当while循环结束时 所有的数据就写到了输出流中
            //使用字节数组数组输出流得到一个  字节数组
            byte[] byteArray = bos.toByteArray();
            jsonStr = new String(byteArray);
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonStr;
    }
    
    

}