android解析json到字符串

时间:2016-06-22 21:14:01

标签: android json

我有一个带有静态JSON变量的jsonString解析器类 我在课堂上有这个代码:

public class JSONParser extends AsyncTask <String, String , String> {

@Override
protected String doInBackground(String... params) {

    HttpURLConnection httpConnection = null;      
    BufferedReader reader = null;      
    StringBuffer buffer = new StringBuffer();
    try {

        URL url = new URL(params[0]);                
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();
        InputStream stream = httpConnection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(stream));
        String line = "";
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }        
    finally {
        if (httpConnection != null)
            httpConnection.disconnect();          
        try {
            if (reader != null)
                reader.close();               
        } catch (IOException e) {
            e.printStackTrace();
        }        }
    return "no Json";    }

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    str = result;        
    try {
        JSONObject jObject = new JSONObject(result);
        aJsonString = jObject.getString("country");
        Log.e("JSON OBJECT" , aJsonString);
    } catch (JSONException e) {
        e.printStackTrace();

,但在MainActivity我正在尝试:

 public TextView tvJsonItem;
        tvJsonItem = (TextView) findViewById(R.id.tvJsonItem);
        final ImageView imageView = (ImageView) findViewById(R.id.imageView);
        Button btnHit= (Button) findViewById(R.id.btnHit);
        assert btnHit != null;
        btnHit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               new JSONParser().execute("http://ip-api.com/json");
                tvJsonItem.setText(JSONParser.str);    
                if (JSONParser.aJsonString.isEmpty()){
                    Toast.makeText(MainActivity.this ,"No Json" , Toast.LENGTH_SHORT).show();
                }

                else if (JSONParser.aJsonString.contains("Israel"))
                {
                    Toast.makeText(MainActivity.this ,JSONParser.aJsonString , Toast.LENGTH_SHORT).show();
                    assert imageView != null;
                    imageView.setImageResource(R.drawable.israel);
                }
            }
        });
    }
}Toast.LENGTH_SHORT).show();
        assert imageView != null;
        imageView.setImageResource(R.drawable.uk);
    }

Main崩溃,抱怨 nullpointerexception 为什么?

0 个答案:

没有答案