android通用JSON解析

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