android通用JSON解析
- 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;
- 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;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.nio.ByteBuffer;
- import java.nio.channels.Channels;
- import java.nio.channels.ReadableByteChannel;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- import org.json.JSONArray;
- import org.json.JSONObject;
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.BaseAdapter;
- import android.widget.ListView;
- import android.widget.TextView;
- import cn.com.pcgroup.android.browser.R;
- public class Information extends Activity {
- private static final String baseUrl = "http://192.168.199.45/1.txt";
- private static final String TAG = Information.class.getSimpleName();
- private static LayoutInflater mInflater;
- private static String json;
- private Map<String, String> infoMap = new HashMap<String, String>();
- private static Map<Index, String> itemMap = new HashMap<Index, String>();
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.online_product_information);
- ListView list = (ListView) findViewById(R.id.list);
- mInflater = getWindow().getLayoutInflater();
- try {
- json = downloadJSON().get();
- Log.v(TAG, json);
- JSONObject jsonObject = new JSONObject(json);
- handleJson(jsonObject, infoMap);
- Index i = new Index();
- i.setKey("image");
- i.setPos(1);
- String result = itemMap.get(i);
- Log.v(TAG, "result = " + result);
- Log.v(TAG, "productId = " + infoMap.get("productId"));
- Log.v(TAG, "itemCount = " + itemCount);
- InforAdapter adapter = new InforAdapter(itemCount);
- list.setAdapter(adapter);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- private void handleJson(JSONObject jsonObject, Map<String, String> infoMap) {
- if (jsonObject == null || infoMap == null)
- return;
- @SuppressWarnings("unchecked")
- Iterator<String> it = jsonObject.keys();
- while (it.hasNext()) {
- String key = it.next();
- JSONArray array = jsonObject.optJSONArray(key);
- // 假如只是JSONObject
- if (array == null)
- infoMap.put(key, jsonObject.optString(key));
- // 是JSONArray,则递归处理
- else {
- handleJsonArray(array, itemMap);
- }
- }
- }
- private static class Index {
- private int pos = 0;
- private String key = new String();
- public Index() {
- }
- public Index(int pos, String key) {
- this.pos = pos;
- this.key = key;
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((key == null) ? 0 : key.hashCode());
- result = prime * result + pos;
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (obj == this)
- return true;
- if (obj instanceof Index)
- return ((Index) obj).pos == pos
- && (((Index) obj).key).equals(key);
- return false;
- }
- public int getPos() {
- return pos;
- }
- public void setPos(int pos) {
- this.pos = pos;
- }
- public String getKey() {
- return key;
- }
- public void setKey(String key) {
- this.key = key;
- }
- }
- private int itemCount = 0;
- private int handleJsonArray(JSONArray array, Map<Index, String> map) {
- if (array == null)
- return itemCount;
- int len = array.length();
- itemCount = len;
- for (int i = 0; i < len; i++) {
- JSONObject obj = (JSONObject) array.opt(i);
- @SuppressWarnings("unchecked")
- Iterator<String> it = obj.keys();
- while (it.hasNext()) {
- String key = it.next();
- JSONArray a = obj.optJSONArray(key);
- if (a != null)
- handleJsonArray(a, itemMap);
- else {
- Index index = new Index(i, key);
- itemMap.put(index, obj.optString(key));
- }
- }
- }
- return itemCount;
- }
- private static class InforAdapter extends BaseAdapter {
- private int count; // 有几条数据
- String[] sa = { "id", "title", "image", "channel" };
- public InforAdapter(int count) {
- this.count = count;
- }
- @Override
- public int getCount() {
- return count;
- }
- @Override
- public Object getItem(int position) {
- return position;
- }
- @Override
- public long getItemId(int position) {
- return position;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- if (convertView == null) {
- convertView = mInflater.inflate(R.layout.information_layout,
- null);
- }
- TextView t = (TextView) convertView.findViewById(R.id.text);
- t.setTextSize(20);
- Index i = new Index(position, "title");
- t.setText(itemMap.get(i));
- return convertView;
- }
- }
- @SuppressWarnings({ "finally", "unused" })
- private String getStringFromServer(final String url){
- ReadableByteChannel channel = null;
- StringBuilder sb = null;
- try {
- URL u = new URL(url);
- HttpURLConnection conn = (HttpURLConnection) u.openConnection();
- channel = Channels.newChannel(conn.getInputStream());
- ByteBuffer buffer = ByteBuffer.allocate(1024);
- sb = new StringBuilder();
- while(channel.read(buffer) != -1){
- buffer.flip();
- while(buffer.hasRemaining())
- sb.append((char)buffer.get());
- buffer.clear();
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }finally{
- try {
- channel.close();
- } catch (IOException e) {
- e.printStackTrace();
- }finally{
- return sb.toString();
- }
- }
- }
- private Future<String> downloadJSON(){
- ExecutorService exec = Executors.newCachedThreadPool();
- class DownLoadTask implements Callable<String>{
- @SuppressWarnings("static-access")
- @Override
- public String call() {
- json = OnlineApiService.getInstance(Information.this).getJSONString(baseUrl);
- return json;
- }
- }
- Future<String> future = exec.submit(new DownLoadTask());
- exec.shutdown();
- return future;
- }
- }
android通用JSON解析的更多相关文章
- 一个.NET通用JSON解析/构建类的实现(c#)转
转自:http://www.cnblogs.com/xfrog/archive/2010/04/07/1706754.html NET通用JSON解析/构建类的实现(c#) 在.NET Framewo ...
- 一个.NET通用JSON解析/构建类的实…
一个.NET通用JSON解析/构建类的实现(c#) 在.NET Framework 3.5中已经提供了一个JSON对象的序列化工具,但是他是强类型的,必须先按JSON对象的格式定义一个类型,并将类型加 ...
- C#字符串数组排序 C#排序算法大全 C#字符串比较方法 一个.NET通用JSON解析/构建类的实现(c#) C#处理Json文件 asp.net使用Jquery+iframe传值问题
C#字符串数组排序 //排序只带字符的数组,不带数字的 private string[] aa ={ "a ", "c ", "b & ...
- Android 之json解析
JSON(JavaScript Object Notation) 定义:字符串 键值对 解析方法有JSON,谷歌GSON,阿里巴巴FastJSON(推荐) 一种轻量级的数据交换格式,具有良好的可读和便 ...
- Android 中Json解析的几种框架(Gson、Jackson、FastJson、LoganSquare)使用与对比
介绍 移动互联网产品与服务器端通信的数据格式,如果没有特殊的需求的话,一般选择使用JSON格式,Android系统也原生的提供了JSON解析的API,但是它的速度很慢,而且没有提供简介方便的接口来提高 ...
- Android之JSON解析
做个Android网络编程的同学一定对于JSON解析一点都不陌生,因为现在我们通过手机向服务器请求资源,服务器给我们返回的数据资源一般都是以JSON格式返回,当然还有一些通过XML格式返回,相对JSO ...
- Android项目--Json解析
在过去的一段时间里,我希望做一个天气的应用,但是由于老版的天气接口已经不能用了.只能更新到2014年3月4日. 不过有些东西,哪来学习一下,也是可以的. 比如:http://m.weather.com ...
- 浅谈Android项目----JSON解析(4种解析技术详解)
json简介 1.概念:json全称是javaScript object Notation,是一种并轻量级的数据交换格式. 2.特点: 1.本质就是具有特定格式的字符串 2.json完全独立于编程语言 ...
- Android okHttp网络请求之Json解析
前言: 前面两篇文章介绍了基于okHttp的post.get请求,以及文件的上传下载,今天主要介绍一下如何和Json解析一起使用?如何才能提高开发效率? okHttp相关文章地址: Android o ...
随机推荐
- JavaScript 与Document
JavaScript JavaScript 是脚本语言, 需要有宿主文件, 他的宿主文件是HTML文件. 可以写在head中 body中 和</heml>之后 一般写在< ...
- 简单的字符串压缩--C代码
#include <stdio.h> #include <string.h> bool compress(char *str) { char *p=str,c; ; if(!s ...
- powerdesigner导出sql
http://jingyan.baidu.com/article/7082dc1c48960ee40a89bd38.html 生成注释 http://wangjingyi.iteye.com/blog ...
- 携手互联网企业10巨头设VC基金
包括小米科技.盛大集团.人人网.掌趣科技.游族网络.龙图游戏.蓝港互动.37游戏.星辉互动娱乐.博雅互动等10家知名互联网企业作为出资人(LP)的优格创投基金近日正式成立. 众所周知,伴随着移动互联网 ...
- Right turn(四川省第七届)
Right turn Time Limit: 1000ms Memory Limit: 65536KB 64-bit integer IO format: %lld Java class n ...
- UTC时间 GMT时间 本地时间 北京时间 时区 夏令时简要说明
1.UTC时间 与 GMT时间 整个地球分为二十四时区,每个时区都有自己的本地时间.为了统一起见,使用一个统一的时间,称为通用协调时(UTC, Universal Time Coordinated). ...
- ES6学习笔记(七)对象的新增方法
1.Object.is() ES5 比较两个值是否相等,只有两个运算符:相等运算符(==)和严格相等运算符(===).它们都有缺点,前者会自动转换数据类型,后者的NaN不等于自身,以及+0等于-0.J ...
- 如何批量ping地址查看网络是否畅通
测试环境搬迁后,需要批量去ping所有机器的IP,看网络是否畅通 测试思路: [weblogic@pays03pre_BankVerify luyantest]$ ping -c 1 172.29.1 ...
- php获取csv数据无乱码
<?php //获取csv数据 function csvencode($file){ if(!is_file($file['tmp_name'])){ ...
- 洛谷 P1013 进制位
P1013 进制位 题目描述 著名科学家卢斯为了检查学生对进位制的理解,他给出了如下的一张加法表,表中的字母代表数字. 例如: + L K V E L L K V E K K V E KL V V E ...