java解析Json中获取Array字段值及嵌套Json对象
Posted MichaelMaDragon
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}
以上是关于java解析Json中获取Array字段值及嵌套Json对象的主要内容,如果未能解决你的问题,请参考以下文章
java中把json怎么转换成数组?
我有一个json数组怎么获取某个字段的对应的对象
在 BigQuery 中提取嵌套 Array/STRUCT JSON 字符串字段的组件
SQL:LATERAL VIEW函数解析多嵌套的json
logstash解析嵌套json的问题
在没有JSON结构的java中解析嵌套JSON