将任意Json字符串解析成Java对象

首先约定,我们可以处理的数据类型。我这里规定了可以处理整形,字符串类型,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数据而不需要实体类的一种方法。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值