Android读取并解析Json

1、不可以在UI线程直接读取网络数据,所以另起线程处理这件事情

public class MainActivity extends ActionBarActivity implements IParseJsonCallback,IParseHtmlCallback{

    public void ParseJsonPage(List<PhaseResultBean> resultList) {
        new ParseJson(this).execute(resultList);
    }

    @Override
    public void ParseJsonDone(List<PhaseResultBean> resultList) {
        //回调函数
    }
}

2、回调接口

package com.neohope.android.gpjj;

import java.util.List;

public interface IParseJsonCallback {
        void ParseJsonDone(List<PhaseResultBean> resultList);
}

3、解析Json类

package com.neohope.android.gpjj;

import android.os.AsyncTask;
import android.util.Log;

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

import java.util.ArrayList;
import java.util.List;

public class ParseJson extends AsyncTask<String,Void,List<PhaseResultBean>>{

    private IParseJsonCallback jsonCallback;

    public ParseJson(IParseJsonCallback jsonCallback)
    {
        this.jsonCallback = jsonCallback;
    }

    @Override
    protected List<PhaseResultBean> doInBackground(String... params) {
        if(params==null)return null;
        List<PhaseResultBean> resultList= new ArrayList<PhaseResultBean>();

        String jsonString = params[0];
        try {
            JSONObject json= new JSONObject(jsonString);
            JSONArray jijinlist = json.getJSONArray("jijinlist");

            for(int i=0;i<jijinlist.length();i++)
            {
                JSONObject JJ= jijinlist.getJSONObject(i);
                PhaseResultBean result = new PhaseResultBean();
                result.code = JJ.getString("code");
                resultList.add(result);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return resultList;
    }

    @Override
    protected void onPostExecute(List<PhaseResultBean> resultList) {
        super.onPostExecute(resultList);
        jsonCallback.ParseJsonDone(resultList);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
}

Comments are closed.