java解析Json中获取Array字段值及嵌套Json对象

1.    Json含有数组时,先把String类型的json串转换的Json对象,通过getJSONArray(key)方法获取其Array部分,然后通过下标和key获取相应子数组里具体的字段值:
String test_arrary = "{\"address\": [{\"addressLine1\": \"Noida\",\"addressLine2\": \"UP\"}],\"firstName\": \"Achyut\",\"lastName\": \"khanna\"}";

public static String getJsonArray(String reqJson) {
 
JSONObject json = null;
String address2 = null;
try {
json = new JSONObject(reqJson);
JSONArray jsonarr= json.getJSONArray("address");
String address1 = jsonarr.getJSONObject(0).getString("addressLine1");
address2 = jsonarr.getJSONObject(0).getString("addressLine2");
System.out.println("address1==" + address1);
System.out.println("address2==" + address2);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return address2;



2.     获取嵌套Json值,即先获取嵌套的内层data为json对象,然后转换为string,然后可以通过getString(key)方式获取data里面的各个字段值:
String test_json = "{\"comm\":{\"comm\":null,\"data\":null,\"unitcode\":\"100001\",\"trxcode\":\"60301\",\"orderno\":\"201803050000023\",\"sendtime\":\"20180307 11:16:18\",\"sendserno\":\"20180307000000000001\",\"channel\":\"pc\",\"sendcode\":\"yxcd\",\"signcode\":\"\"},\"data\":{\"orderno\":\"201803050000023\",\"urgentflag\":null,\"loanamt\":null,\"servamt\":null,\"allamt\":\"50000.00\",\"chnsname\":\"张立男\",\"buybackreason\":null,\"filetrans\":\"0\",\"filename\":null,\"filepasswd\":null,\"filesize\":null}}";

public static String queryData(String reqJson, String data) {
String str = null;
if (null != data && !data.equals("")) {
try {
str = new JSONObject(reqJson).getJSONObject(data).toString();
} catch (JSONException e) {
e.printStackTrace();
LogUtil.info(e.getMessage());
}
} else str = "Json报文data部分为空!";
System.out.println("data ==="+str);
return str;
}
posted @ 2020-07-22 23:16  MichaelMaDragon  阅读(5788)  评论(0编辑  收藏  举报