无法解析JSON文件中的数据

时间:2015-11-02 17:31:59

标签: android json android-asynctask

我是JSON的新手。我试图在我的应用程序中解析一个简单的JSON文件。

文件是:

[
{
    "itemName": "Backtrack",
    "messgae": "Backtrack is going to start soon.Participants please report to the venues",
  },
{
    "itemName": "Lan-Gaming",
    "messgae": "Lan-Gaming is going to start soon.Participants please report to the venues",
  },
{
    "itemName": "Deadlock",
    "messgae": "Deadlock is going to start soon.Participants please report to the venues",
      }
]    

据我所知,我尝试了但应用程序崩溃了。它提供了以下控制台:

11-02 22:48:36.955 4913-4929/? 
E/AndroidRuntime: FATAL EXCEPTION:    AsyncTask #1
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime: Process: com.defcomdevs.jsonparsing, PID: 4913
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at android.os.AsyncTask$3.done(AsyncTask.java:300)
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:841)
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:  Caused by: java.lang.NullPointerException
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at com.defcomdevs.jsonparsing.MainActivity$ProgressTask.doInBackground(MainActivity.java:87)
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at com.defcomdevs.jsonparsing.MainActivity$ProgressTask.doInBackground(MainActivity.java:45)
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
11-02 22:48:36.955 4913-4929/? E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:841) 
11-02 22:48:36.955 559-886/? W/ActivityManager:   Force finishing activity com.defcomdevs.jsonparsing/.MainActivity

基本上在后台函数中发生错误。我的java文件是:

package com.defcomdevs.jsonparsing;

 import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
 import android.widget.ListView;
import android.widget.SimpleAdapter;

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

import java.util.ArrayList;
import java.util.HashMap;


public class MainActivity extends ListActivity {

private Context context;
private static String url = "http://192.168.1.3/test.json";  //url for the terget page

private static final String VTYPE = "Type";
private static final String ITEMID = "ITEM";
private static final String ITEMMSG="MESSAGE";
private static final String VCOLOR = "Color";
private static final String FUEL = "Fuel";
private static final String TREAD = "Tread";    //properties of the page

ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

ListView lv;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new ProgressTask(MainActivity.this).execute();
}

private class ProgressTask extends AsyncTask<String, Void, Boolean> {

    private ProgressDialog dialog;  //spinning symbol @ loading

    private ListActivity activity;

    private Context context;

    public ProgressTask(ListActivity activity) {
        this.activity = activity;
        context = activity;
        dialog = new ProgressDialog(context);
    }

    @Override
    protected void onPreExecute() {
        this.dialog.setMessage("Fetching data...Please wait");
        this.dialog.show(); //shows the dialog before parsing data from page
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }

        ListAdapter adapter = new SimpleAdapter(context, jsonlist,
                R.layout.list_item, new String[]{ITEMID,ITEMMSG}, new int[]{R.id.vehicleType,
                R.id.vehicleColor});

        setListAdapter(adapter);

        lv = getListView();  //todo after the data has been obtained
    }

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

        JSONParser jParser = new JSONParser();

        JSONArray json = jParser.getJSONFromUrl(url); //parser to parse from page

        for (int i = 0; i < json.length(); i++) {
            try {
                JSONObject c = json.getJSONObject(i); //each node is assigned here
                String name = c.getString("itemName");
                String mssg = c.getString("messgae");
                   //details of the entity

                HashMap<String, String> map = new HashMap<String, String>();

                map.put(ITEMID, name);
                map.put(ITEMMSG, mssg);
                jsonlist.add(map);

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

        return false;
    }
}
}

JSON解析器:

  package com.defcomdevs.jsonparsing;



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

    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 android.util.Log;

 public class JSONParser {

static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";

public JSONParser() {
}

public JSONArray getJSONFromUrl(String url) {

    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);

    try{
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if(statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.e("==>", "Failed to download file");
        }
    } catch(ClientProtocolException e) {
        e.printStackTrace();
    } catch(IOException e) {
        e.printStackTrace();
    }

    try {
        jarray = new JSONArray(builder.toString());
    } catch(JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jarray;
}
}

请帮忙。

1 个答案:

答案 0 :(得分:1)

Json

中的语法错误

你的json中有语法错误。 messgae结尾处不应该有逗号。这是正确的json:

    [
    {
        "itemName": "Backtrack",
        "messgae": "Backtrack is going to start soon.Participants please report to the venues"
      },
    {
        "itemName": "Lan-Gaming",
        "messgae": "Lan-Gaming is going to start soon.Participants please report to the venues"
      },
    {
        "itemName": "Deadlock",
        "messgae": "Deadlock is going to start soon.Participants please report to the venues"
      }
    ]