Android JSON解析一般有三种方法。
第一种:JSON本身提供的包org.json
其中提供了JSONArray、JSONObject、JSONStringer、JSONTokener等类
第二种:Google提供的GSON工具
需要将gson包放置在应用内才可以使用,常用的方法gson.fromJson(xxx),该方法有多种参数。具体请参考GSON文档
第三种:阿里巴巴提供的第三方开源库fastJson
同样,需要fastJson工具包
第一种的解析流程:
1.客户端向服务器端发送请求
2.服务器端从数据库中返回JSON数据
3.客户端将返回的流转换为String类型
4.如果JSON String是以“{”开头的,则表示是一个JSONObject。通过以下方法将String数据转化为JSONObject对象:
JSONObject(String json)
Creates a new JSONObject with name/value mappings from the JSON string.
再通过以下方法可以得到Key对应的Value,Value可以是JSONArray、JSONObject、String、Boolean、int等类型:
其中参数name为Key。
同理,假如是以"["开头的,则表示是一个JSONArray,通过以下方法将String数据转化为JSONArray对象:
JSONArray(String json)
Creates a new JSONArray with values from the JSON string.
通过以下方法可以解析JSONArray数据:
假如JSONarray中的数据是一个复杂数据,例如:[{"key1":value1 , "key2":value2 , "key3":value3 : ....},{"key11":value11 , "key22":value22 , "key33":value33 : ....},{}....]
可以考虑将其存放为List<Map<String,Object>>中
数组中JsonObject对象可以通过以下方法遍历解析:
Iterator<String> keys()
Returns an iterator of the String names in this object.
具体方法例如:
Iterator<String> keyIter = jsonObject.keys();
String key;
Object value;
Map<String, Object> valueMap = new HashMap<String, Object>();
while (keyIter.hasNext())
{
key = (String) keyIter.next();
value = jsonObject.get(key);
valueMap.put(key, value);
}