Json从URL解析

时间:2013-11-19 15:32:37

标签: java android

我运行时遇到java.lang.NullPointerException。有谁知道为什么会发生这种情况以及如何解决它?

如果您有任何建议,请查看我的代码并告诉我。

{"begin":[{"id":1,"name":"Andy","size":1}],"open":[{"id":1,"name":"Tom","size":2}]}

片段

public class MainFragment extends Fragment {
    public MainFragment() {}

    //URL to get JSON Array
    private String url = "URL...";

    //JSON Node Names
    private static final String TAG_BEGIN = "begin";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_SIZE = "size";

    JSONArray begin = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        new JSONParse().execute();

        return rootView;
    }

    private class JSONParse extends AsyncTask<String, String, JSONObject> {
        private ProgressDialog pDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(HomeActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        @Override
        protected JSONObject doInBackground(String... args) {
            JSONParser jParser = new JSONParser();

            // Getting JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url);
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            pDialog.dismiss();
            try {
                // Getting JSON Array
                begin = json.getJSONArray(TAG_BEGIN);
                JSONObject c = begin.getJSONObject(0);

                // Storing  JSON item in a Variable
                String id = c.getString(TAG_ID);
                String name = c.getString(TAG_NAME);
                String size = c.getString(TAG_SIZE);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }
}

JSONParser

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

错误:

E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

FATAL EXCEPTION: main

java.lang.NullPointerException
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:399)
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:373)

哪个是......

begin = json.getJSONArray(TAG_BEGIN);

和...

private class JSONParse extends AsyncTask<String, String, JSONObject> {

编辑(答案)

JSONParser

在JSONParser内部,我将代码更改为:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpUriRequest request = new HttpGet(url);
        request.setHeader("Accept", "application/json");

        HttpResponse response = httpClient.execute(request);
        HttpEntity httpEntity = response.getEntity();

        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

onPostExecute内部

JSONArray begin = json.getJSONArray(TAG_BEGIN);
 for (int i = 0; i < begin(); i++) {
  try {

   JSONObject b = = begin(i);

   String id = b.getString(TAG_ID);
   String name = b.getString(TAG_NAME);
   String size = b.getString(TAG_SIZE);

  } catch (JSONException e) {
   e.printStackTrace();
  }
 }

3 个答案:

答案 0 :(得分:0)

首先确保您的JSONObject不为null。然后根据类型逐行逐行横向。

JSONArray begin = json.getJSONArray(TAG_BEGIN);

然后可能做这样的事情?

for(int n = 0; n < begin.length(); n++)
{
    JSONObject object = begin.getJSONObject(n);
    // query through the array
    String id = object.getString(TAG_ID);
    String name = object.getString(TAG_NAME);
    String size = object.getString(TAG_SIZE);
    //Now do something with the strings
}

当然你会用TAG_OPEN做同样的事情。让我知道如果这有效,我会很乐意尽可能地帮助。

答案 1 :(得分:0)

错误显示您的http请求的返回字符串不仅是json数据

包括<!DOCTYPE之类的内容

请检查您是否请求正确的URL,并且服务器正确处理请求

您可以使用浏览器访问您请求的网址并查看返回结果

答案 2 :(得分:0)

我没有使用片段,但这里是类似的解决方案。

更改您的网址和密钥值,以便从json中检索值。我没有你的网址,所以我使用了其他一些。请检查一下。相同的概念,除了我没有使用片段,但这个json解析代码工作正常。

首先,您必须在主线程异常

上处理网络

添加:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

在你班上,

将此添加到ManiFestFile:

<uses-permission android:name="android.permission.INTERNET"/>

MainActivity.Java

    package com.example.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Making HTTP request
        String url = "http://api.androidhive.info/contacts/";
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        try {
            // Getting JSON Array
            JSONArray begin = json.getJSONArray("contacts");
            JSONObject c = begin.getJSONObject(0);

            // Storing  JSON item in a Variable
            String id = c.getString("id");
            String name = c.getString("name");
            String size = c.getString("email");

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

JSONParser.Java

package com.example.test;

import android.os.StrictMode;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}