Table of Contents
Judge whether a certain Key exists in JSONObject
Check whether the key exists in the json string
The following introduces my own situation
Home Java javaTutorial How to determine whether a JSONObject contains a certain key in Java?

How to determine whether a JSONObject contains a certain key in Java?

May 08, 2023 pm 12:25 PM
java key jsonobject

Judge whether a certain Key exists in JSONObject

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

Judge whether the vesion attribute exists in jsonObject

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

Check whether the key exists in the json string

Original intention, due to work needs, the two units need interface data docking. Unit one needs to send a json data string to unit two. However, the fields in the json data sent by unit one are uncertain. They explained that the customer entered the data on the system. For those fields, they will bring those fields, and for those fields that customers do not enter, they will not bring them by default. Unit one requires unit two, and the default value of this detected field will be empty!

So as unit two, we need to find a way to detect which fields unit one did not bring over. The solution that immediately came to mind at first was to use exception handling, because the program itself reported not found when tested, so it is understandable to use exception handling. . . If you use an exception, after thinking about it, you can only capture not found, and then just leave the captured field blank in finally and it will be ok.

Then the problem comes. I tried the abnormal situation and found that there were too many finallys to deal with; so I thought of using another method, using a containsKey() function of json to determine whether it exists in the json string. This key is whether this field exists; of course, there are other functions that can also be judged, this is based on the json package introduced by yourself.

The following introduces my own situation

The imported jar package is:

How to determine whether a JSONObject contains a certain key in Java?

First of all, the json package I imported:

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
Copy after login

The code is as follows:

/**
	 * 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();
	}
Copy after login

As can be seen from the code, each field is processed with the containsKey() function, so there is no need to worry about which field cannot be found in the j'son string sent by the unit. The situation has arrived.

The above is the detailed content of How to determine whether a JSONObject contains a certain key in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Unpatchable Yubico two-factor authentication key vulnerability breaks the security of most Yubikey 5, Security Key, and YubiHSM 2FA devices Unpatchable Yubico two-factor authentication key vulnerability breaks the security of most Yubikey 5, Security Key, and YubiHSM 2FA devices Sep 04, 2024 pm 06:32 PM

An unpatchable Yubico two-factor authentication key vulnerability has broken the security of most Yubikey 5, Security Key, and YubiHSM 2FA devices. The Feitian A22 JavaCard and other devices using Infineon SLB96xx series TPMs are also vulnerable.All

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles