如何解析Android中的JSON?
3 回答
白猪掌柜的
TA贡献1893条经验 获得超10个赞
Android拥有解析内置json所需的所有工具。示例如下,不需要GSON或类似的东西。
获取您的JSON:
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());HttpPost httppost = new HttpPost (http://someJSONUrl/jsonWebService);// Depends on your web servicehttppost.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,那又怎样?
创建一个JSONObject:
JSONObject jObject = new JSONObject(result);
获取特定字符串
String aJsonString = jObject.getString("STRINGNAME");
获取特定的布尔值
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
获取特定的整数
int aJsonInteger = jObject.getInt("INTEGERNAME");
得到一个特定的长
long aJsonLong = jObject.getLong("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 }}
添加回答
举报
0/150
提交
取消