如何parsingAndroid中的JSON
我在哪里可以find关于如何parsingAndroid中的JSON提要的分步说明? 我只是一个想学习的Android初学者。
Android有你需要parsingjson内置的所有工具。 示例如下,不需要GSON或类似的东西。
获取您的JSON:
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httppost = new HttpPost(http://someJSONUrl/jsonWebService); // Depends on your web service httppost.setHeader("Content-type", "application/json"); InputStream inputStream = null; String result = null; try { HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (Exception e) { // Oops } finally { try{if(inputStream != null)inputStream.close();}catch(Exception squish){} }
现在你有你的JSON,那么是什么?
创build一个JSONObject :
JSONObject jObject = new JSONObject(result);
得到一个特定的string
String aJsonString = jObject.getString("STRINGNAME");
得到一个特定的布尔值
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
得到一个特定的整数
int aJsonInteger = jObject.getInt("INTEGERNAME");
得到一个特定的长
long aJsonLong = jObject.getBoolean("LONGNAME");
获得一个特定的双
double aJsonDouble = jObject.getDouble("DOUBLENAME");
获取特定的JSONArray :
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
从数组中获取项目
for (int i=0; i < jArray.length(); i++) { try { JSONObject oneObject = jArray.getJSONObject(i); // Pulling items from the array String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray"); String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY"); } catch (JSONException e) { // Oops } }
-
编写JSONparsing器类
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; } }
-
parsingJSON数据一旦你创build了parsing器类,接下来就是要知道如何使用这个类。 下面我解释如何使用parsing器类来parsingjson(在这个例子中)。
2.1。 将所有这些节点名称存储在variables中:在联系人json中,我们有诸如姓名,电子邮件,地址,性别和电话号码之类的项目。 所以首先是将所有这些节点名称存储在variables中。 打开您的主要活动类,并声明将所有节点名称存储在静态variables中。
// url to make request private static String url = "http://api.9android.net/contacts"; // JSON Node names private static final String TAG_CONTACTS = "contacts"; private static final String TAG_ID = "id"; private static final String TAG_NAME = "name"; private static final String TAG_EMAIL = "email"; private static final String TAG_ADDRESS = "address"; private static final String TAG_GENDER = "gender"; private static final String TAG_PHONE = "phone"; private static final String TAG_PHONE_MOBILE = "mobile"; private static final String TAG_PHONE_HOME = "home"; private static final String TAG_PHONE_OFFICE = "office"; // contacts JSONArray JSONArray contacts = null;
2.2。 使用parsing器类来获取JSONObject并循环遍历每个json项目。 下面我创build一个JSONParser类的实例,并使用循环,我循环通过每个JSON项目,并最终将每个JSON数据存储在variables中。
// Creating JSON Parser instance JSONParser jParser = new JSONParser(); // getting JSON string from URL JSONObject json = jParser.getJSONFromUrl(url); try { // Getting Array of Contacts contacts = json.getJSONArray(TAG_CONTACTS); // looping through All Contacts for(int i = 0; i < contacts.length(); i++){ JSONObject c = contacts.getJSONObject(i); // Storing each json item in variable String id = c.getString(TAG_ID); String name = c.getString(TAG_NAME); String email = c.getString(TAG_EMAIL); String address = c.getString(TAG_ADDRESS); String gender = c.getString(TAG_GENDER); // Phone number is agin JSON Object JSONObject phone = c.getJSONObject(TAG_PHONE); String mobile = phone.getString(TAG_PHONE_MOBILE); String home = phone.getString(TAG_PHONE_HOME); String office = phone.getString(TAG_PHONE_OFFICE); } } catch (JSONException e) { e.printStackTrace(); }
我已经为你编写了一个简单的例子,并注明了源代码。 这个例子展示了如何抓取实时json和parsing到一个JSONObject中来提取细节:
try{ // Create a new HTTP Client DefaultHttpClient defaultClient = new DefaultHttpClient(); // Setup the get request HttpGet httpGetRequest = new HttpGet("http://example.json"); // Execute the request in the client HttpResponse httpResponse = defaultClient.execute(httpGetRequest); // Grab the response BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); // Instantiate a JSON object from the request response JSONObject jsonObject = new JSONObject(json); } catch(Exception e){ // In your production code handle any errors and catch the individual exceptions e.printStackTrace(); }
一旦你有了JSONObject,就可以参考SDK了解如何提取你需要的数据。