
参见英文答案 > How to parse JSON in Java 31个
如何解析AndroID中的JsON提要?
解决方法:
Note: this answer has not been updated since 2013. The suggested way to download the Json is not recommended for androID anymore as the http clIEnt has been removed from the sdk as of API 23.
However, the parsing logic below still applIEs
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 }} 总结 以上是内存溢出为你收集整理的如何解析Android中的JSON?全部内容,希望文章能够帮你解决如何解析Android中的JSON?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)