1、得到json,通过不断转换,得到想要的key值,此方法较为麻烦:json-lib
{"alibaba_aliqin_fc_sms_num_send_response":{"result":{"err_code":"0","model":"100750884853^1101174334520","success":true},"request_id":"z2cey4146sxj"}} //得到对应的code值 public static int getOneString(String body) { JSONObject jsonObject = JSONObject.fromObject(body); JSONObject jsonObject1 = JSONObject.fromObject(jsonObject.getString("alibaba_aliqin_fc_sms_num_send_response")); String errCode = JSONObject.fromObject(jsonObject1.getString("result")).getString("err_code"); return Integer.parseInt(errCode); }
2、org.json:
官网:http://developer.android.com/reference/org/json/package-summary.html
3、代码方法:
/** * 将Javabean转换为Map * * @param javaBean * javaBean * @return Map对象 */ public static Map toMap(Object javaBean) { Map result = new HashMap(); Method[] methods = javaBean.getClass().getDeclaredMethods(); for (Method method : methods) { try { if (method.getName().startsWith("get")) { String field = method.getName(); field = field.substring(field.indexOf("get") + 3); field = field.toLowerCase().charAt(0) + field.substring(1); Object value = method.invoke(javaBean, (Object[]) null); result.put(field, null == value ? "" : value.toString()); } } catch (Exception e) { e.printStackTrace(); } } return result; } /** * 将Json对象转换成Map * * @param jsonObject * json对象 * @return Map对象 * @throws JSONException */ public static Map toMap(String jsonString) throws JSONException { JSONObject jsonObject = new JSONObject(jsonString); Map result = new HashMap(); Iterator iterator = (Iterator) jsonObject.keys(); String key = null; String value = null; while (iterator.hasNext()) { key = (String) iterator.next(); value = jsonObject.getString(key); result.put(key, value); } return result; } /** * 将JavaBean转换成JSONObject(通过Map中转) * * @param bean * javaBean * @return json对象 */ public static JSONObject toJSON(Object bean) { return new JSONObject(toMap(bean)); } /** * 将Map转换成Javabean * * @param javabean * javaBean * @param data * Map数据 */ public static Object toJavaBean(Object javabean, Map data) { Method[] methods = javabean.getClass().getDeclaredMethods(); for (Method method : methods) { try { if (method.getName().startsWith("set")) { String field = method.getName(); field = field.substring(field.indexOf("set") + 3); field = field.toLowerCase().charAt(0) + field.substring(1); method.invoke(javabean, new Object[] { data.get(field) }); } } catch (Exception e) { } } return javabean; } /** * JSONObject到JavaBean * * @param bean * javaBean * @return json对象 * @throws ParseException * json解析异常 * @throws JSONException */ public static void toJavaBean(Object javabean, String jsonString) throws ParseException, JSONException { JSONObject jsonObject = new JSONObject(jsonString); Map map = toMap(jsonObject.toString()); toJavaBean(javabean, map); }