json使用uri解析android中的listview

时间:2016-07-16 09:59:59

标签: json parsing

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

//URL to get JSON Array
private static String url = "http://jsonplaceholder.typicode.com/posts";
//JSON Node Names
// private static final String TAG_OS = "Employee";
private static final String TAG_USER= "userId";
private static final String TAG_NAME = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_BODY = "body";

JSONArray android = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    list = new ArrayList<HashMap<String, String>>();

    Btngetdata = (Button)findViewById(R.id.getdata);
    Btngetdata.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            new JSONParse().execute();

        }
    });

}

private class JSONParse extends AsyncTask<String, String, JSONObject> {
    private ProgressDialog pDialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        ver = (TextView)findViewById(R.id.user);
        name = (TextView)findViewById(R.id.id);
        api = (TextView)findViewById(R.id.titile);
        body =(TextView)findViewById(R.id.body);
        pDialog = new ProgressDialog(MainActivity.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 from URL
           android = json.getJSONArray("");
            for(int i = 0; i < android.length(); i++){
                JSONObject c = android.getJSONObject(i);

                // Storing  JSON item in a Variable
                String ver = c.getString(TAG_USER);
                String name = c.getString(TAG_NAME);
                String api = c.getString(TAG_TITLE);
                String body =c.getString(TAG_BODY);

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

                map.put(TAG_USER, ver);
                map.put(TAG_NAME, name);
                map.put(TAG_TITLE, api);
                map.put(TAG_BODY, body);

                list.add(map);
                List=(ListView)findViewById(R.id.list);

                ListAdapter adapter = new SimpleAdapter(MainActivity.this, list,
                        R.layout.list_v,
                        new String[] { TAG_USER,TAG_NAME, TAG_TITLE,TAG_BODY }, new int[] {
                        R.id.user,R.id.id, R.id.titile,R.id.body});

                List.setAdapter(adapter);
                List.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        Toast.makeText(MainActivity.this, "You Clicked at "+list.get(+position).get("name"), Toast.LENGTH_SHORT).show();

                    }
                });

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

    }
}

}



 json parse:-


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;

}

}

Logcat here

java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArrayorg.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at  com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:134)
at com.example.mind.sqlitedatabase.MainActivity$JSONParse.onPostExecute(MainActivity.java:103)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

实际上,当我点击get按钮调用uri进行json解析时,我遇到了问题 但是当在android设备中json = null解析...

1 个答案:

答案 0 :(得分:0)

在这里我使用了Volley库,它处理你手动完成的所有事情(Asynctask,json的httprequest)。

我希望它可以帮到你

 // JsonObject request    

   public void getJSONFromUrl(String url) {

    RequestQueue queue = Volley.newRequestQueue(getActivity());
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
            url, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d("Response", "Response" + response);

               //handle the json response
                    handleResponse(response);
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("Error", "Error: " + error.getMessage());
        }
    });
    queue.add(jsonObjReq);
 }

//使用JsonHelper类从

public void handleResponse(JSONObject response) {

    Map<String, Object> map = new HashMap<>();
    if(response != null){
        try {

         // JsonObject to Map
            map = JsonHelper.toMap(response);

         // boolean isSuccess = map.get("success")
           // if(isSuccess){

            //}

            if (map.size() != 0){
                // use the data 
            }
            Log.d("MAp","map" + map);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

下面的类将帮助将json响应转换为MAP,从map转换为json。

https://gist.github.com/codebutler/2339666

复制
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;

public class JsonHelper {
public static Object toJSON(Object object) throws JSONException {
    if (object instanceof Map) {
        JSONObject json = new JSONObject();
        Map map = (Map) object;
        for (Object key : map.keySet()) {
            json.put(key.toString(), toJSON(map.get(key)));
        }
        return json;
    } else if (object instanceof Iterable) {
        JSONArray json = new JSONArray();
        for (Object value : ((Iterable)object)) {
            json.put(value);
        }
        return json;
    } else {
        return object;
    }
}

public static boolean isEmptyObject(JSONObject object) {
    return object.names() == null;
}

public static Map<String, Object> getMap(JSONObject object, String key) throws JSONException {
    return toMap(object.getJSONObject(key));
}

public static Map<String, Object> toMap(JSONObject object) throws JSONException {
    Map<String, Object> map = new HashMap();
    Iterator keys = object.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        map.put(key, fromJson(object.get(key)));
    }
    return map;
}

public static List toList(JSONArray array) throws JSONException {
    List list = new ArrayList();
    for (int i = 0; i < array.length(); i++) {
        list.add(fromJson(array.get(i)));
    }
    return list;
}

private static Object fromJson(Object json) throws JSONException {
    if (json == JSONObject.NULL) {
        return null;
    } else if (json instanceof JSONObject) {
        return toMap((JSONObject) json);
    } else if (json instanceof JSONArray) {
        return toList((JSONArray) json);
    } else {
        return json;
     }
  }
}

凌空图书馆使用情况  http://www.androidhive.info/2014/09/android-json-parsing-using-volley/