android通用JSON解析
2016-04-13 17:33
435 查看
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;
}
}
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的一个service
- cordova开发插件步骤及小结(android插件)
- android.util.log(Log.v()Log.d()Log.i()Log.w()和Log.e())
- Pro Android学习笔记(一五四):传感器(4):陀螺仪、加速传感器
- Android蓝牙BLE低功耗相关简单总结
- android中ListView控件&&onItemClick事件中获取listView传递的数据
- Android程序的安全系统 apk获得root权限
- Android动画之旅一Android动画基本介绍
- Android mediaPlayer属性详解
- Android 5.0以后版本打开“有权查看使用情况的应用”
- android xml之Drawable 篇 --------shape和selector和layer-list的
- Android开发笔记(八十五)手机数据库Realm
- android 5.0以上获取前台应用的包名
- 初试Android的MVP框架
- Android群英传--绘图机制和处理技巧(二)
- Android - Fragments
- Android APK反编译就这么简单 详解(附图)
- Android:让EditText不自动获取焦点
- Android——SQLite数据库(二)升级数据库、增、删、改、查、事务
- Android 更改系统DataPicker分割线颜色和距离