首先约定,我们可以处理的数据类型。我这里规定了可以处理整形,字符串类型,JsonObject和JsonArray类型。这在实际应用中是很常见的。代码如下:
public HashMap<String, Object> getMapFromJsonString(String json)
{
HashMap<String, Object> output_json = new HashMap<String, Object>();
try {
JSONObject jo = new JSONObject(json);
Iterator it = jo.keys();
while(it.hasNext())
{
String str = (String)it.next();
if( jo.get(str) instanceof Integer) {
output_json.put(str, jo.get(str));
}
else if ( jo.get(str) instanceof String ) {
output_json.put(str, jo.get(str));
}
else if ( jo.get(str) instanceof JSONObject ) {
output_json.put(str, getMapFromJsonString(jo.get(str).toString()));
}
else if ( jo.get(str) instanceof JSONArray ) {
ArrayList<Object> data = new ArrayList<Object>() ;
for(int i = 0; i < ((JSONArray)jo.get(str)).length(); i++)
{
data.add(getObjectFromJsonObject(((JSONArray)jo.get(str)).get(i))); //getMapFromJsonString(jo.get(str).toString()))
}
output_json.put(str, data);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return output_json;
}
public Object getObjectFromJsonObject(Object json)
{
if(json == null) return null;
if( json instanceof Integer) {
return json;
}
else if ( json instanceof String ) {
return json;
}
else if ( json instanceof JSONObject ) {
return getMapFromJsonString(json.toString());
}
else if ( json instanceof JSONArray ) {
ArrayList<Object> data = new ArrayList<Object>() ;
for(int i = 0; i < ((JSONArray)json).length(); i++)
{
try {
data.add(getObjectFromJsonObject(((JSONArray)json).get(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
return data;
} else {
return null;
}
}
getMapFromJsonString方法接受json字符串,返回一个Java对象。这里用了迭代的方法,可能不够效率,但也清晰明了。getObjectFromJsonObject是一个辅助方法。在这里,json会被转换成HashMap对象。其中JsonObject会被转成HashMap,JsonArray会被转成JsonArray。
使用方法为:
String json = "{\"code\":0,\"message\":\"成功\",\"resultData\":{\"items\":[{\"formId\":1,\"description\":\"请假\",\"formName\":\"请假申请\"},{\"formId\":2,\"description\":\"测试\",\"formName\":\"测试表单\"}]}}";
Log.e("abc", getMapFromJsonString(json).toString());
以下为输出结果
{message=成功, resultData={items=[{formId=1, description=请假, formName=请假申请}, {formId=2, description=测试, formName=测试表单}]}, code=0}
注意,{}为HashMap,[]为ArrayList,转化成功。
当然,如果你需要扩充可以转化的数据类型,添加到处理方法即可,非常方便和实用。这提供了解析json数据而不需要实体类的一种方法。