我有一个json对象是这样的:
{ Yg7R_: { fld_invoice: "Yg7R_" fld_order_id: "5" fld_orders: { 4: { fld_oiid: "4" fld_date: "2014-03-27 00:00:00" fld_name: "20140327_H5epz2y4OB_IMG_20140326_020341.jpg" fld_loc: "../orders/oid_5/" } } } LldP_: { fld_invoice: "LldP_" fld_order_id: "7" fld_orders: { 6: { fld_oiid: "6" fld_date: "2014-03-27 00:00:00" fld_name: "20140327_SovH7Xf3n2_IMG_20140326_020418.jpg" fld_loc: "../orders/oids_7/" } } } NYEO: { fld_invoice: "NYEO" fld_order_id: "24" fld_orders: { 27: { fld_oiid: "27" fld_date: "2014-03-27 00:00:00" fld_name: "20140327_duLLsssVWA_IMG_20140326_020341.jpg" fld_loc: "orders/oid_24/" } 28: { fld_oiid: "28" fld_date: "2014-03-27 00:00:00" fld_name: "20140327_F8ayA4vWrP_IMG_20140326_020405.jpg" fld_loc: "orders/oid_24/" } 29: { fld_oiid: "29" fld_date: "2014-03-27 00:00:00" fld_name: "20140327_1FlYnuNbtr_IMG_20140326_020418.jpg" fld_loc: "orders/oid_24/" } } } }
我试图这样解析:
// result is the above json object. for(int i = 0; i < result.length(); i++){ try { invoice = result.getJSONArray(<Some name here>); // this name is dynamic Log.d("invoice "+i, invoice); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
但是我不知道如何访问动态名称。我们如何解析这样的JSON
-注意-Ya的 所有值都带有引号,例如:“ Yg&R_”
试试这个动态的JSON解析器
private void parseJson(JSONObject data) { if (data != null) { Iterator<String> it = data.keys(); while (it.hasNext()) { String key = it.next(); try { if (data.get(key) instanceof JSONArray) { JSONArray arry = data.getJSONArray(key); int size = arry.length(); for (int i = 0; i < size; i++) { parseJson(arry.getJSONObject(i)); } } else if (data.get(key) instanceof JSONObject) { parseJson(data.getJSONObject(key)); } else { System.out.println(key + ":" + data.getString(key)); } } catch (Throwable e) { try { System.out.println(key + ":" + data.getString(key)); } catch (Exception ee) { } e.printStackTrace(); } } } }