Json解析网络请求数据

网络请求得到的数据不能直接拿来用,需要解析之后再用
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

import com.jredu.study.R;
import com.jredu.study.entity.SportNews;

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

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class JsonActivity extends AppCompatActivity {
    WebView webView;
    Button jsonBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json);
        webView = (WebView) findViewById(R.id.jsonWebView);
        jsonBtn = (Button) findViewById(R.id.jsonButton);
        jsonBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        parseJSON();
                    }
                }).start();
            }
        });
    }
    private void parseJSON() {
        HttpURLConnection urlConnection = null;
        InputStream is;
        StringBuilder sb = new StringBuilder();
        try {
            URL url = new URL("http://apis.baidu.com/txapi/tiyu/tiyu?num=10&page=1&word=%E6%9E%97%E4%B8%B9");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(5*1000);
            urlConnection.setReadTimeout(5*1000);
            urlConnection.setRequestProperty("apikey","自己申请的apikey");
            urlConnection.connect();
            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                is = urlConnection.getInputStream();
                byte[] bytes = new byte[1024];
                int i = 0;
                while ((i = is.read(bytes)) != -1){
                    sb.append(new String(bytes,0,i,"utf-8"));
                }
                is.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        Message message = handler.obtainMessage(1,sb.toString());
        handler.sendMessage(message);
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                String s = (String) msg.obj;
                webView.getSettings().setJavaScriptEnabled(true);
                webView.getSettings().setDefaultTextEncodingName("utf-8");
                webView.loadDataWithBaseURL(null,s,"text/html","utf-8",null);

                List list = parseJsonToList(s);
                SportNews sn = list.get(0);
                Toast.makeText(getApplication(),sn.getTitle(),Toast.LENGTH_SHORT).show();
            }
        }
    };
    private List parseJsonToList(String s){
        List list = new ArrayList();
        try {
            JSONObject obj = new JSONObject(s);
            String code = obj.getString("code");
            String msg = obj.getString("msg");
            JSONArray array = obj.getJSONArray("newslist");
            for (int i = 0; i < array.length(); i ++) {
                JSONObject object = array.getJSONObject(i);
                SportNews news = new SportNews(
                        object.getString("ctime"),
                        object.getString("title"),
                        object.getString("description"),
                        object.getString("picUrl"),
                        object.getString("url")
                );
                list.add(news);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }
}

你可能感兴趣的:(Android)