我正在尝试通过 Android 上的 JSON 从 API 中提取信息。我已经成功下载了信息,现在我需要将其放入带有“类别”标签的 JSONArray 中。最终这将进入列表视图。这是我的代码:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class jsonParser {
//initialize
static JSONObject object =null;
public jsonParser(){
}
public JSONObject getJSONfromURL (String url){
//HTTP call
try{
URLConnection connection = new URL(url).openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()), 2048 * 16);
StringBuffer builder = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
String blah = builder.toString();
//Parsing string into JSONArray
JSONObject object = new JSONObject ( new String(builder.toString()) );
Log.e("success","created object: " + object);
} catch(Exception e){
Log.e("Http Error","Error in http connection " + e.toString());
}
return object;
}
}
这是Logcat:
05-12 16:57:54.040: E/success(9625): created object: {"Categories":[{"id":"2","name":"Glass Repair"},{"id":"3","name":"Appliance Repair"},{"id":"4","name":"Air Conditioning"},{"id":"5","name":"Community Involvement"},{"id":"6","name":"Electrical"},{"id":"7","name":"Flooring"},{"id":"8","name":"Heating Repair"},{"id":"9","name":"Landscaping"},{"id":"10","name":"Plumbing"},{"id":"11","name":"Remodeling\/Renovation"},{"id":"12","name":"Window Coverings"}]}
05-12 16:57:54.040: E/JSON Variable(9625): json returns this value: null
05-12 16:57:54.070: E/Test JSON(9625): JSON s returns: null
05-12 16:57:54.070: W/dalvikvm(9625): threadid=1: thread exiting with uncaught exception (group=0x416bf438)
05-12 16:57:54.070: E/AndroidRuntime(9625): FATAL EXCEPTION: main
05-12 16:57:54.070: E/AndroidRuntime(9625): java.lang.NullPointerException
05-12 16:57:54.070: E/AndroidRuntime(9625): at com.example.hstnc_activity.DisplayServiceActivity$Request.onPostExecute(DisplayServiceActivity.java:104)
05-12 16:57:54.070: E/AndroidRuntime(9625): at com.example.hstnc_activity.DisplayServiceActivity$Request.onPostExecute(DisplayServiceActivity.java:1)
05-12 16:57:54.070: E/AndroidRuntime(9625): at android.os.AsyncTask.finish(AsyncTask.java:631)
05-12 16:57:54.070: E/AndroidRuntime(9625): at android.os.AsyncTask.access$600(AsyncTask.java:177)
05-12 16:57:54.070: E/AndroidRuntime(9625): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
05-12 16:57:54.070: E/AndroidRuntime(9625): at android.os.Handler.dispatchMessage(Handler.java:99)
05-12 16:57:54.070: E/AndroidRuntime(9625): at android.os.Looper.loop(Looper.java:137)
05-12 16:57:54.070: E/AndroidRuntime(9625): at android.app.ActivityThread.main(ActivityThread.java:4918)
05-12 16:57:54.070: E/AndroidRuntime(9625): at java.lang.reflect.Method.invokeNative(Native Method)
05-12 16:57:54.070: E/AndroidRuntime(9625): at java.lang.reflect.Method.invoke(Method.java:511)
05-12 16:57:54.070: E/AndroidRuntime(9625): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
05-12 16:57:54.070: E/AndroidRuntime(9625): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
05-12 16:57:54.070: E/AndroidRuntime(9625): at dalvik.system.NativeStart.main(Native Method)
最后是 JSON 信息(使用 jsonlint.com 获取):
{
"Categories": [
{
"id": "2",
"name": "Glass Repair"
},
{
"id": "3",
"name": "Appliance Repair"
},
{
"id": "4",
"name": "Air Conditioning"
},
{
"id": "5",
"name": "Community Involvement"
},
{
"id": "6",
"name": "Electrical"
},
{
"id": "7",
"name": "Flooring"
},
{
"id": "8",
"name": "Heating Repair"
},
{
"id": "9",
"name": "Landscaping"
},
{
"id": "10",
"name": "Plumbing"
},
{
"id": "11",
"name": "Remodeling/Renovation"
},
{
"id": "12",
"name": "Window Coverings"
}
]
}
这是异步方法:
public class Request extends AsyncTask<String, Void, JSONObject> {
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;
private ProgressDialog dialog =
new ProgressDialog(DisplayServiceActivity.this);
protected void onPreExecute() {
dialog = new ProgressDialog(DisplayServiceActivity.this);
dialog.setMessage("Getting your info real quick... Please wait...");
dialog.show();
}
protected JSONObject doInBackground(String... params) {
json = jParser.getJSONfromURL(url);
Log.e("JSON Variable", "json returns this value: " + json);
return json;
}
protected void onPostExecute(JSONObject s) {
super.onPostExecute(s);
dialog.dismiss();
Log.e("Test JSON","JSON s returns: " + s);
try {
directory = s.getJSONArray("Categories");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i< directory.length(); i++){
String str_id = directory.optString(i, "id");
String str_name = directory.optString(i, "name");
displayCatList(str_id, str_name);
Log.e("Test directory","Directory returns: " + json);
}
}
}
我感谢所有的帮助!