1. ackage cn.com.pcgroup.<a href="http://lib.csdn.net/base/15" class="replace_word" title="Android知识库" target="_blank" style="color:#df3434; font-weight:bold;">android</a>.browser.module.onlineproduct;
  2. import <a href="http://lib.csdn.net/base/17" class="replace_word" title="Java EE知识库" target="_blank" style="color:#df3434; font-weight:bold;">java</a>.io.IOException;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5. import java.nio.ByteBuffer;
  6. import java.nio.channels.Channels;
  7. import java.nio.channels.ReadableByteChannel;
  8. import java.util.ArrayList;
  9. import java.util.HashMap;
  10. import java.util.Iterator;
  11. import java.util.List;
  12. import java.util.Map;
  13. import java.util.concurrent.Callable;
  14. import java.util.concurrent.ExecutorService;
  15. import java.util.concurrent.Executors;
  16. import java.util.concurrent.Future;
  17. import org.json.JSONArray;
  18. import org.json.JSONObject;
  19. import android.app.Activity;
  20. import android.os.Bundle;
  21. import android.util.Log;
  22. import android.view.LayoutInflater;
  23. import android.view.View;
  24. import android.view.ViewGroup;
  25. import android.widget.BaseAdapter;
  26. import android.widget.ListView;
  27. import android.widget.TextView;
  28. import cn.com.pcgroup.android.browser.R;
  29. public class Information extends Activity {
  30. private static final String baseUrl = "http://192.168.199.45/1.txt";
  31. private static final String TAG = Information.class.getSimpleName();
  32. private static LayoutInflater mInflater;
  33. private static String json;
  34. private Map<String, String> infoMap = new HashMap<String, String>();
  35. private static Map<Index, String> itemMap = new HashMap<Index, String>();
  36. @Override
  37. protected void onCreate(Bundle savedInstanceState) {
  38. super.onCreate(savedInstanceState);
  39. setContentView(R.layout.online_product_information);
  40. ListView list = (ListView) findViewById(R.id.list);
  41. mInflater = getWindow().getLayoutInflater();
  42. try {
  43. json = downloadJSON().get();
  44. Log.v(TAG, json);
  45. JSONObject jsonObject = new JSONObject(json);
  46. handleJson(jsonObject, infoMap);
  47. Index i = new Index();
  48. i.setKey("image");
  49. i.setPos(1);
  50. String result = itemMap.get(i);
  51. Log.v(TAG, "result = " + result);
  52. Log.v(TAG, "productId = " + infoMap.get("productId"));
  53. Log.v(TAG, "itemCount = " + itemCount);
  54. InforAdapter adapter = new InforAdapter(itemCount);
  55. list.setAdapter(adapter);
  56. } catch (Exception e) {
  57. throw new RuntimeException(e);
  58. }
  59. }
  60. private void handleJson(JSONObject jsonObject, Map<String, String> infoMap) {
  61. if (jsonObject == null || infoMap == null)
  62. return;
  63. @SuppressWarnings("unchecked")
  64. Iterator<String> it = jsonObject.keys();
  65. while (it.hasNext()) {
  66. String key = it.next();
  67. JSONArray array = jsonObject.optJSONArray(key);
  68. // 假如只是JSONObject
  69. if (array == null)
  70. infoMap.put(key, jsonObject.optString(key));
  71. // 是JSONArray,则递归处理
  72. else {
  73. handleJsonArray(array, itemMap);
  74. }
  75. }
  76. }
  77. private static class Index {
  78. private int pos = 0;
  79. private String key = new String();
  80. public Index() {
  81. }
  82. public Index(int pos, String key) {
  83. this.pos = pos;
  84. this.key = key;
  85. }
  86. @Override
  87. public int hashCode() {
  88. final int prime = 31;
  89. int result = 1;
  90. result = prime * result + ((key == null) ? 0 : key.hashCode());
  91. result = prime * result + pos;
  92. return result;
  93. }
  94. @Override
  95. public boolean equals(Object obj) {
  96. if (obj == this)
  97. return true;
  98. if (obj instanceof Index)
  99. return ((Index) obj).pos == pos
  100. && (((Index) obj).key).equals(key);
  101. return false;
  102. }
  103. public int getPos() {
  104. return pos;
  105. }
  106. public void setPos(int pos) {
  107. this.pos = pos;
  108. }
  109. public String getKey() {
  110. return key;
  111. }
  112. public void setKey(String key) {
  113. this.key = key;
  114. }
  115. }
  116. private int itemCount = 0;
  117. private int handleJsonArray(JSONArray array, Map<Index, String> map) {
  118. if (array == null)
  119. return itemCount;
  120. int len = array.length();
  121. itemCount = len;
  122. for (int i = 0; i < len; i++) {
  123. JSONObject obj = (JSONObject) array.opt(i);
  124. @SuppressWarnings("unchecked")
  125. Iterator<String> it = obj.keys();
  126. while (it.hasNext()) {
  127. String key = it.next();
  128. JSONArray a = obj.optJSONArray(key);
  129. if (a != null)
  130. handleJsonArray(a, itemMap);
  131. else {
  132. Index index = new Index(i, key);
  133. itemMap.put(index, obj.optString(key));
  134. }
  135. }
  136. }
  137. return itemCount;
  138. }
  139. private static class InforAdapter extends BaseAdapter {
  140. private int count; // 有几条数据
  141. String[] sa = { "id", "title", "image", "channel" };
  142. public InforAdapter(int count) {
  143. this.count = count;
  144. }
  145. @Override
  146. public int getCount() {
  147. return count;
  148. }
  149. @Override
  150. public Object getItem(int position) {
  151. return position;
  152. }
  153. @Override
  154. public long getItemId(int position) {
  155. return position;
  156. }
  157. @Override
  158. public View getView(int position, View convertView, ViewGroup parent) {
  159. if (convertView == null) {
  160. convertView = mInflater.inflate(R.layout.information_layout,
  161. null);
  162. }
  163. TextView t = (TextView) convertView.findViewById(R.id.text);
  164. t.setTextSize(20);
  165. Index i = new Index(position, "title");
  166. t.setText(itemMap.get(i));
  167. return convertView;
  168. }
  169. }
  170. @SuppressWarnings({ "finally", "unused" })
  171. private String getStringFromServer(final String url){
  172. ReadableByteChannel channel = null;
  173. StringBuilder sb = null;
  174. try {
  175. URL u = new URL(url);
  176. HttpURLConnection conn = (HttpURLConnection) u.openConnection();
  177. channel = Channels.newChannel(conn.getInputStream());
  178. ByteBuffer buffer = ByteBuffer.allocate(1024);
  179. sb = new StringBuilder();
  180. while(channel.read(buffer) != -1){
  181. buffer.flip();
  182. while(buffer.hasRemaining())
  183. sb.append((char)buffer.get());
  184. buffer.clear();
  185. }
  186. } catch (Exception e) {
  187. throw new RuntimeException(e);
  188. }finally{
  189. try {
  190. channel.close();
  191. } catch (IOException e) {
  192. e.printStackTrace();
  193. }finally{
  194. return sb.toString();
  195. }
  196. }
  197. }
  198. private Future<String> downloadJSON(){
  199. ExecutorService exec = Executors.newCachedThreadPool();
  200. class DownLoadTask implements Callable<String>{
  201. @SuppressWarnings("static-access")
  202. @Override
  203. public String call() {
  204. json = OnlineApiService.getInstance(Information.this).getJSONString(baseUrl);
  205. return json;
  206. }
  207. }
  208. Future<String> future = exec.submit(new DownLoadTask());
  209. exec.shutdown();
  210. return future;
  211. }
  212. }

android通用JSON解析的更多相关文章

  1. 一个.NET通用JSON解析/构建类的实现(c#)转

    转自:http://www.cnblogs.com/xfrog/archive/2010/04/07/1706754.html NET通用JSON解析/构建类的实现(c#) 在.NET Framewo ...

  2. 一个.NET通用JSON解析/构建类的实…

    一个.NET通用JSON解析/构建类的实现(c#) 在.NET Framework 3.5中已经提供了一个JSON对象的序列化工具,但是他是强类型的,必须先按JSON对象的格式定义一个类型,并将类型加 ...

  3. C#字符串数组排序 C#排序算法大全 C#字符串比较方法 一个.NET通用JSON解析/构建类的实现(c#) C#处理Json文件 asp.net使用Jquery+iframe传值问题

    C#字符串数组排序   //排序只带字符的数组,不带数字的 private   string[]   aa   ={ "a ", "c ", "b & ...

  4. Android 之json解析

    JSON(JavaScript Object Notation) 定义:字符串 键值对 解析方法有JSON,谷歌GSON,阿里巴巴FastJSON(推荐) 一种轻量级的数据交换格式,具有良好的可读和便 ...

  5. Android 中Json解析的几种框架(Gson、Jackson、FastJson、LoganSquare)使用与对比

    介绍 移动互联网产品与服务器端通信的数据格式,如果没有特殊的需求的话,一般选择使用JSON格式,Android系统也原生的提供了JSON解析的API,但是它的速度很慢,而且没有提供简介方便的接口来提高 ...

  6. Android之JSON解析

    做个Android网络编程的同学一定对于JSON解析一点都不陌生,因为现在我们通过手机向服务器请求资源,服务器给我们返回的数据资源一般都是以JSON格式返回,当然还有一些通过XML格式返回,相对JSO ...

  7. Android项目--Json解析

    在过去的一段时间里,我希望做一个天气的应用,但是由于老版的天气接口已经不能用了.只能更新到2014年3月4日. 不过有些东西,哪来学习一下,也是可以的. 比如:http://m.weather.com ...

  8. 浅谈Android项目----JSON解析(4种解析技术详解)

    json简介 1.概念:json全称是javaScript object Notation,是一种并轻量级的数据交换格式. 2.特点: 1.本质就是具有特定格式的字符串 2.json完全独立于编程语言 ...

  9. Android okHttp网络请求之Json解析

    前言: 前面两篇文章介绍了基于okHttp的post.get请求,以及文件的上传下载,今天主要介绍一下如何和Json解析一起使用?如何才能提高开发效率? okHttp相关文章地址: Android o ...

随机推荐

  1. Create the Project

    https://docs.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspn ...

  2. SQL解析XML文件

    DECLARE @idoc int DECLARE @doc varchar(max) SET @doc ='<?xml version="1.0" encoding=&qu ...

  3. HDU-5307 He is Flying (FFT)

    Problem DescriptionJRY wants to drag racing along a long road. There are n sections on the road, the ...

  4. JS数组去重的6种算法实现

    1.遍历数组法 最简单的去重方法,实现思路:新建一新数组,遍历传入数组,值不在新数组就加入该新数组中:注意点:判断值是否在数组的方法"indexOf"是ECMAScript5 方法 ...

  5. Oracle-02-数据库概述

    一.数据库用途 用于存放数据的软件 当中Application server重要,将数据存在表中每一个表关系就能够反映不同表之间数据的关系,比方淘宝用户注冊.商品买卖等数据存在操作系统的目录中,不便于 ...

  6. 归并排序_分治算法 (白书P226)

    #include<iostream> #include<cstdio> #include<algorithm> using namespace std; int a ...

  7. idle-实现清屏

    最近在学习python的时候,需要用到ubuntu的python idle.这个工具可以测试python语法.但是呢,在使用的过程中遇到了一个问题.就是随着你的输入,你会发现这个输入会停留在这个界面的 ...

  8. VS书签的应用

    为某一行添加书签,方便快速定位. 添加书签, 查找上一个书签, 查找下一个书签, 清空所有书签. 有意思.

  9. pix格式的一些摸索

    作者:朱金灿 来源:http://blog.csdn.net/clever101 以前因为工作关系研究过PCI的系统格式pix,但是遗留了一些问题,最近又想重新解决这些问题.研究了一天,有些收获,但是 ...

  10. notepad++go语法高亮文件

    notepad++go语法高亮文件 下载 右键另存为下载后在语言栏中的自定义面板中直接导入,重启即可