首頁 >Java >java教程 >如何在Java中判斷JSONObject是否包含某個鍵(key)?

如何在Java中判斷JSONObject是否包含某個鍵(key)?

王林
王林轉載
2023-05-08 12:25:074137瀏覽

判斷JSONObject是否存在某個Key

JSONObject jsonObj = new JSONObject();
jsonObj.put("version", "1.0.0"); // 版本号
jsonObj.put("encoding", "UTF-8"); // 编码方式

判斷jsonObject是否存在vesion屬性

jsonObj.has("version");  // 返回true

檢查json字串中是否存在該key

##初衷,是由於工作需要,兩個單位需要介面資料對接,單位一需要發送json資料串到單位二,然而單位一發送的json資料中的欄位不確定,聽他們解釋說,客戶在系統上輸那些字段,他們就會把那些字段帶過來,然後那些客戶不輸入的字段,他們就會默認不帶。單位一要求單位二,將此檢測出不帶的字段預設值為空!

所以身為單位二,我們就需要想辦法偵測到單位一哪些欄位沒帶過來。起初立刻想到的辦法就是用異常狀況處理,因為程式本身測試的時候就報not found了,所以用異常處理情有可原吧。 。 。如果用異常的,想了一下只能捕捉到not found之後,在finally裡將捕捉到的這個字段直接置空就ok了。

那麼問題來了,對異常的情況試了一下,finally太多不好處理;所以就想了用另外一個方法,用json的一個containsKey()函數來判斷json字串中是否存在這個key,即是否存在這個字段;當然,還有其他函數也可以判斷的,這個根據自己引入的json包了。

下面介紹我自己的情況

導入的jar包為:

如何在Java中判斷JSONObject是否包含某個鍵(key)?

首先我導入的json包:

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

程式碼如下:

/**
	 * 9903接口解析json数据并且将数据进行入库
	 * 
	 * @author syp
	 * @time 2019年7月3日11:49:02
	 */
	public String dateRepository(String jsonData) {
		Log4jBean.logger.info("开始处理入库程序!");
		ReadConfig.PullConfigXml();  //启动配置文件
		DBUtils db = new DBUtils();  
		JSONObject json=new JSONObject();
		String jsonStr=jsonData.substring(44, jsonData.length());
		JSONObject jsonObject = JSONObject.fromObject(jsonStr);
		JSONObject jsonCard=jsonObject.getJSONObject("cardid_info")
		JSONObject jsonObu = jsonObject.getJSONObject("obu_info");
		JSONObject jsonUser=jsonObject.getJSONObject("user_info");
		JSONObject jsonCar = jsonObject.getJSONObject("car_info");		
		//准备将所有json数据信息入开卡集合表ETC_OPEN_CARD_COLLECTION
		JSONObject jsonAccno = jsonObject.getJSONObject("accno_info");
			String allSql = "insert into ETC_OPEN_CARD_COLLECTION(ACCOUNTID,LINKMOBILE,ACCNO_USERNAME,CERTSN,POSID,GENTIME,TRX_SERNO,EMPLOYEEID,ORG_TRX_SERNO,CARD_ID,CARDTYPE,CARD_BRAND,CARD_MODEL,AGENCYID,CARD_USERID,VEHICLEID,ENABLETIME,EXPIRETIME,ISSUEDTYPE,CHANNELID,ISSUEDTIME,CARD_STATUS,STATUSCHANGETIME,CARD_OPERATION,OBU_ID,OBU_BRAND,OBU_MODEL,OBU_USERID,OBU_VEHICLEID,OBU_ENABLETIME,OBU_EXPIRETIME,REGISTEREDTYPE,REGISTEREDCHANNELID,REGISTEREDTIME,INSTALLTYPE,INSTALLCHANNELID,INSTALLTIME,OBU_STATUS,OBU_STATUSCHANGETIME,OBU_OPERATION,USER_ID,USERTYPE,USER_NAME,USERIDTYPE,USERIDNUM,USER_TEL,USER_ADDRESS,USER_REGISTEREDTYPE,USER_CHANNELID,USER_REGISTEREDTIME,DEPARTMENT,AGENTNAME,AGENTIDTYPE,AGENTIDNUM,USER_STATUS,USER_STATUSCHANGETIME,USER_OPERATION,CAR_ID,CAR_TYPE,CAR_USERID,OWNERNAME,OWNERIDTYPE,OWNERIDNUM,OWNERTEL,CAR_ADDRESS,CAR_CONTACT,CAR_REGISTEREDTYPE,CAR_CHANNELID,CAR_REGISTEREDTIME,VEHICLETYPE,VEHICLEMODEL,USECHARACTER,VIN,ENGINENUM,REGISTERDATE,ISSUEDATE,FILENUM,APPROVEDCOUNT,TOTALMASS,MAINTENANCEMASS,PERMITTEDWEIGHT,OUTSIDEDIMENSIONS,PERMITTEDTOWWEIGHT,TESTRECORD,WHEELCOUNT,AXLECOUNT,AXLEDISTANCE,AXISTYPE,CAR_OPERATION) values('"
					+ (jsonAccno.containsKey("accountid")?jsonAccno.getString("accountid"):"")
					+ "','"
					+ (jsonAccno.containsKey("linkmobile")?jsonAccno.getString("linkmobile"):"") 
					+ "','"
					+ (jsonAccno.containsKey("username")?jsonAccno.getString("username"):"") 
					+ "','"
					+ (jsonAccno.containsKey("certsn")?jsonAccno.getString("certsn"):"") 
					+ "','"
					+ (jsonAccno.containsKey("posid")?jsonAccno.getString("posid"):"")
					+ "','"
					+ (jsonAccno.containsKey("gentime")?jsonAccno.getString("gentime"):"") 
					+ "','"
					+ (jsonAccno.containsKey("trx_serno")?jsonAccno.getString("trx_serno"):"") 
					+ "','"
					+ (jsonAccno.containsKey("employeeid")?jsonAccno.getString("employeeid"):"") 
					+ "','"
					+ (jsonAccno.containsKey("org_trx_serno")?jsonAccno.getString("org_trx_serno"):"") 
					+ "','"
					+ (jsonCard.containsKey("id")?jsonCard.getString("id"):"")
					+ "','"
					+ (jsonCard.containsKey("cardType")?jsonCard.getString("cardType"):"") 
					+ "','"
					+ (jsonCard.containsKey("brand")?jsonCard.getString("brand"):"") 
					+ "','"
					+ (jsonCard.containsKey("model")?jsonCard.getString("model"):"") 
					+ "','"
					+ (jsonCard.containsKey("agencyId")?jsonCard.getString("agencyId"):"") 
					+ "','"
					+ (jsonCard.containsKey("userId")?jsonCard.getString("userId"):"") 
					+ "','"
					+ (jsonCard.containsKey("vehicleId")?jsonCard.getString("vehicleId"):"") 
					+ "','"
					+ (jsonCard.containsKey("enableTime")?jsonCard.getString("enableTime"):"") 
					+ "','"
					+ (jsonCard.containsKey("expireTime")?jsonCard.getString("expireTime"):"") 
					+ "','"
					+ (jsonCard.containsKey("issuedType")?jsonCard.getString("issuedType"):"") 
					+ "','"
					+ (jsonCard.containsKey("channelId")?jsonCard.getString("channelId"):"") 
					+ "','"
					+ (jsonCard.containsKey("issuedTime")?jsonCard.getString("issuedTime"):"") 
					+ "','"
					+ (jsonCard.containsKey("status")?jsonCard.getString("status"):"") 
					+ "','"
					+ (jsonCard.containsKey("statusChangeTime")?jsonCard.getString("statusChangeTime"):"")
					+ "','"
					+ (jsonCard.containsKey("operation")?jsonCard.getString("operation"):"")	
					+ "','"
					+ (jsonObu.containsKey("id")?jsonObu.getString("id"):"")
					+ "','"
					+ (jsonObu.containsKey("brand")?jsonObu.getString("brand"):"")
					+ "','"
					+ (jsonObu.containsKey("model")?jsonObu.getString("model"):"")
					+ "','"
					+ (jsonObu.containsKey("userId")?jsonObu.getString("userId"):"")
					+ "','"
					+ (jsonObu.containsKey("vehicleId")?jsonObu.getString("vehicleId"):"")
					+ "','"
					+ (jsonObu.containsKey("enableTime")?jsonObu.getString("enableTime"):"")
					+ "','"
					+ (jsonObu.containsKey("expireTime")?jsonObu.getString("expireTime"):"")
					+ "','"
					+ (jsonObu.containsKey("registeredType")?jsonObu.getString("registeredType"):"")
					+ "','"
					+ (jsonObu.containsKey("registeredChannelId")?jsonObu.getString("registeredChannelId"):"")
					+ "','"
					+ (jsonObu.containsKey("registeredTime")?jsonObu.getString("registeredTime"):"")
					+ "','"
					+ (jsonObu.containsKey("installType")?jsonObu.getString("installType"):"")
					+ "','"
					+ (jsonObu.containsKey("installChannelId")?jsonObu.getString("installChannelId"):"")
					+ "','"
					+ (jsonObu.containsKey("installTime")?jsonObu.getString("installTime"):"")
					+ "','"
					+ (jsonObu.containsKey("status")?jsonObu.getString("status"):"")
					+ "','"
					+ (jsonObu.containsKey("statusChangeTime")?jsonObu.getString("statusChangeTime"):"")
					+ "','"
					+ (jsonObu.containsKey("operation")?jsonObu.getString("operation"):"")
					+ "','"
					+ (jsonUser.containsKey("id")?jsonUser.getString("id"):"")
					+ "','" 
					+ (jsonUser.containsKey("userType")?jsonUser.getString("userType"):"") 
					+ "','" 
					+ (jsonUser.containsKey("userName")?jsonUser.getString("userName"):"") 
					+ "','" 
					+ (jsonUser.containsKey("userIdType")?jsonUser.getString("userIdType"):"") 
					+ "','" 
					+ (jsonUser.containsKey("userIdNum")?jsonUser.getString("userIdNum"):"") 
					+ "','" 
					+ (jsonUser.containsKey("tel")?jsonUser.getString("tel"):"") 
					+ "','" 
					+ (jsonUser.containsKey("address")?jsonUser.getString("address"):"") 
					+ "','" 
					+ (jsonUser.containsKey("registeredType")?jsonUser.getString("registeredType"):"") 
					+ "','" 
					+ (jsonUser.containsKey("channelId")?jsonUser.getString("channelId"):"") 
					+ "','" 
					+ (jsonUser.containsKey("registeredTime")?jsonUser.getString("registeredTime"):"") 
					+ "','" 
					+ (jsonUser.containsKey("department")?jsonUser.getString("department"):"") 
					+ "','" 
					+ (jsonUser.containsKey("agentName")?jsonUser.getString("agentName"):"") 
					+ "','" 
					+ (jsonUser.containsKey("agentIdType")?jsonUser.getString("agentIdType"):"") 
					+ "','" 
					+ (jsonUser.containsKey("agentIdNum")?jsonUser.getString("agentIdNum"):"") 
					+ "','" 
					+ (jsonUser.containsKey("status")?jsonUser.getString("status"):"") 
					+ "','" 
					+ (jsonUser.containsKey("statusChangeTime")?jsonUser.getString("statusChangeTime"):"") 
					+ "','" 
					+ (jsonUser.containsKey("operation")?jsonUser.getString("operation"):"")
					+ "','" 
					+ (jsonCar.containsKey("id")?jsonCar.getString("id"):"") 
					+ "','"
					+ (jsonCar.containsKey("type")?jsonCar.getString("type"):"")  
					+ "','"
					+ (jsonCar.containsKey("userId")?jsonCar.getString("userId"):"")  
					+ "','"+
					(jsonCar.containsKey("ownerName")?jsonCar.getString("ownerName"):"")  
					+ "','"+
					(jsonCar.containsKey("ownerIdType")?jsonCar.getString("ownerIdType"):"")  
					+ "','"+
					(jsonCar.containsKey("ownerIdNum")?jsonCar.getString("ownerIdNum"):"")  
					+ "','"+
					(jsonCar.containsKey("ownerTel")?jsonCar.getString("ownerTel"):"")  
					+ "','"+
					(jsonCar.containsKey("address")?jsonCar.getString("address"):"")  
					+ "','"+
					(jsonCar.containsKey("contact")?jsonCar.getString("contact"):"")  
					+ "','"+
					(jsonCar.containsKey("registeredType")?jsonCar.getString("registeredType"):"")  
					+ "','"+
					(jsonCar.containsKey("channelId")?jsonCar.getString("channelId"):"")  
					+ "','"+
					(jsonCar.containsKey("registeredTime")?jsonCar.getString("registeredTime"):"")  
					+ "','"+
					(jsonCar.containsKey("vehicleType")?jsonCar.getString("vehicleType"):"")  
					+ "','"+
					(jsonCar.containsKey("vehicleModel")?jsonCar.getString("vehicleModel"):"")  
					+ "','"+
					(jsonCar.containsKey("useCharacter")?jsonCar.getString("useCharacter"):"")  
					+ "','"+
					(jsonCar.containsKey("VIN")?jsonCar.getString("VIN"):"")  
					+ "','"+
					(jsonCar.containsKey("engineNum")?jsonCar.getString("engineNum"):"")  
					+ "','"+
					(jsonCar.containsKey("registerDate")?jsonCar.getString("registerDate"):"")  
					+ "','"+
					(jsonCar.containsKey("issueDate")?jsonCar.getString("issueDate"):"")  
					+ "','"+
					(jsonCar.containsKey("fileNum")?jsonCar.getString("fileNum"):"")  
					+ "','"+
					(jsonCar.containsKey("approvedCount")?jsonCar.getString("approvedCount"):"") 
					+ "','"+
					(jsonCar.containsKey("totalMass")?jsonCar.getString("totalMass"):"")  
					+ "','"+
					(jsonCar.containsKey("maintenanceMass")?jsonCar.getString("maintenanceMass"):"")  
					+ "','"+
					(jsonCar.containsKey("permittedWeight")?jsonCar.getString("permittedWeight"):"")  
					+ "','"+
					(jsonCar.containsKey("outsideDimensions")?jsonCar.getString("outsideDimensions"):"")  
					+ "','"+
					(jsonCar.containsKey("permittedTowWeight")?jsonCar.getString("permittedTowWeight"):"")  
					+ "','"+
					(jsonCar.containsKey("testRecord")?jsonCar.getString("testRecord"):"")  
					+ "','"+
					(jsonCar.containsKey("wheelCount")?jsonCar.getString("wheelCount"):"")  
					+ "','"+
					(jsonCar.containsKey("axleCount")?jsonCar.getString("axleCount"):"")  
					+ "','"+
					(jsonCar.containsKey("axleDistance")?jsonCar.getString("axleDistance"):"")  
					+ "','"+
					(jsonCar.containsKey("axisType")?jsonCar.getString("axisType"):"")  
					+ "','"+
					(jsonCar.containsKey("operation")?jsonCar.getString("operation"):"") 
					+ "')";
			int allParam = db.updateMethod(allSql, null);
			if (allParam > 0) {
				Log4jBean.logger.info("开卡集合数据写入开卡集合表成功!");
				json.put("return_msg", "处理成功!");
				json.put("return_code", "0");
			} else {
				Log4jBean.logger.error("开卡集合数据写入开卡集合表失败!");
				json.put("return_msg", "处理失败!");
				json.put("return_code", "-1");
			}
		return json.toString();
	}

透過程式碼可以看出,每個欄位都用containsKey()函數做了處理,這樣就不用害怕單位一發過來的j'son字串中哪個欄位找不到的情況了。

以上是如何在Java中判斷JSONObject是否包含某個鍵(key)?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除