JSON入门之二:org.json的基本用法 分类: C_OHTERS ...

本文深入探讨了Java中用于JSON处理的org.json库,包括构建JSON文本的方法、读取JSON文本内容以及相关类的使用。通过实例展示了如何使用JSONObject和JSONStringer创建、读取JSON对象,并对比了两者之间的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


java中用于解释json的主流工具有org.json、json-lib与gson,本文介绍org.json的应用。

官方文档:

http://www.json.org/java/

http://developer.android.com/reference/org/json/package-summary.html

 

1、主要类

Classes


JSONArray

A dense indexed sequence of values. 

JSONObject

A modifiable set of name/value mappings. 

JSONStringer

Implements toString() and toString()

JSONTokener

Parses a JSON (RFC 4627) encoded string into the corresponding object. 

Exceptions


JSONException

Thrown to indicate a problem with the JSON API. 

 

2、构建一个JSON文本的方法

(1)使用JSONObject的构造方法,然后toString。

创建一个JSONObject对象后,再使用put(String, Object)方法添加键值对。

toString()方法将JSONObject对象按照JSON的标准格式进行封装。

(2)使用JSONStringer创建JSON文本。

String myString = new JSONStringer().object()   
.key("name")  
.value("小猪")   
.endObject()  
.toString();
完整程序如下:

package com.ljh.jsondemo;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.junit.Test;

public class JSONObjectTest {

	@Test
	public void test() {
		System.out.println(prepareJSONObject());
		System.out.println(prepareJSONObject2());
	}
	
	private static String prepareJSONObject(){
		JSONObject studentJSONObject = new JSONObject();
		try {
			studentJSONObject.put("name", "Jason");
			studentJSONObject.put("id", 20130001);
			studentJSONObject.put("phone", "13579246810");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return studentJSONObject.toString();
	}
	
	private static String prepareJSONObject2(){
		JSONStringer jsonStringer = new JSONStringer();
		try {
			jsonStringer.object();
			jsonStringer.key("name");
			jsonStringer.value("Jason");
			jsonStringer.key("id");
			jsonStringer.value(20130001);
			jsonStringer.key("phone");
			jsonStringer.value("13579246810");
			jsonStringer.endObject();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jsonStringer.toString();
	}

}
输出结果如下:

{"id":20130001,"phone":"13579246810","name":"Jason"}
{"name":"Jason","id":20130001,"phone":"13579246810"}

结论:

(1)使用JSONObject构造的JSON文本顺序杂乱,使用JSONStringer则按顺序排列。

(2)关于二者之间的比较,android官方文档认为:

 Most application developers should use those methods directly and disregard this API. For example:

 JSONObject object = ...
 String json = object.toString();

Stringers only encode well-formed JSON strings. In particular:

  • The stringer must have exactly one top-level array or object.
  • Lexical scopes must be balanced: every call to array() must have a matching call to endArray() and every call to object() must have a matching call to endObject().
  • Arrays may not contain keys (property names).
  • Objects must alternate keys (property names) and values.
  • Values are inserted with either literal value calls, or by nesting arrays or objects.
Calls that would result in a malformed JSON string will fail with a  JSONException .

This class provides no facility for pretty-printing (ie. indenting) output. To encode indented output, use toString(int) or toString(int).

Some implementations of the API support at most 20 levels of nesting. Attempts to create more than 20 levels of nesting may fail with a JSONException.

Each stringer may be used to encode a single top level value. Instances of this class are not thread safe. Although this class is nonfinal, it was not designed for inheritance and should not be subclassed. In particular, self-use by overrideable methods is not specified. See Effective Java Item 17, "Design and Document or inheritance or else prohibit it" for further information.

即:

一般情况下使用JSONObject即可,但对于一些嵌套的JSON,某些JSONArray没有key,只有value等特殊情况,则使用JSONStringer.


3、读取JSON文本内容。

使用JSONTokener类的相关方法。

package com.ljh.jsondemo;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.Test;

public class JSONTokenerTEst {

	@Test
	public void test() {
		System.out.println(getJSONContent());
	}
	
	private static String JSONText = "{\"id\":20130001,\"phone\":\"13579246810\",\"name\":\"Jason\"}";
	
	private static String getJSONContent(){
		JSONTokener jsonTokener = new JSONTokener(JSONText); 
		JSONObject studentJSONObject;
		String name = null;
		int id = 0;
		String phone = null;
		try {
			studentJSONObject = (JSONObject) jsonTokener.nextValue();
			name = studentJSONObject.getString("name");
			id = studentJSONObject.getInt("id");
			phone = studentJSONObject.getString("phone");
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return name + "  " + id + "   " + phone;
	}
}
输出结果如下:

Jason  20130001   13579246810

事实上,使用JSONObject的构造方法也可直接创建JSONObject对象。

private static String getJSONContent2(){
	String name = null;
	int id = 0;
	String phone = null;
	try {
		JSONObject studentJSONObject = new JSONObject(JSONText); 
		name = studentJSONObject.getString("name");
		id = studentJSONObject.getInt("id");
		phone = studentJSONObject.getString("phone");
		
	} catch (JSONException e) {
		e.printStackTrace();
	}
	return name + "  " + id + "   " + phone;
}

总结:单纯使用JSONObject可以解决大部分的JSON处理问题。




版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/lujinhong2/p/4637341.html

import ctypes import logging import win32com.client # 创建 WMI 对象 wmi = win32com.client.GetObject("winmgmts:") logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", handlers=[logging.StreamHandler()] ) logger = logging.getLogger(__name__) # 获取 USB 设备 usb_devices = wmi.ExecQuery("SELECT * FROM Win32_PnPEntity WHERE PNPDeviceID LIKE 'USB%'") def is_admin() -> bool: """检查是否以管理员权限运行""" try: return ctypes.windll.shell32.IsUserAnAdmin() except Exception as e: logger.error(f"权限检查失败: {str(e)}") return False # 打印设备信息 for device in usb_devices: print(f"Device ID: {device.PNPDeviceID}, Description: {device.Description}") # python D:\ATRI\AirtestIDE\Pimax_test\pimax_test\testcase\Ohters\test.py # 禁用 USB 设备 for device in usb_devices: if "USB\\VID_34A4&PID_0040\\P407B0D2004C2900002" in device.PNPDeviceID: # 替换为你的设备 ID try: # 调用 Disable 方法 is_admin() result = device.Disable() if result == 0: print(f"Disabled device: {device.PNPDeviceID}") else: print(f"Failed to disable device: Error code {result}") except Exception as e: print(f"Failed to disable device: {e}") # 启用 USB 设备 for device in usb_devices: if "USB\\VID_34A4&PID_0040\\P407B0D2004C2900002" in device.PNPDeviceID: # 替换为你的设备 ID try: # 调用 Enable 方法 is_admin() result = device.Enable() if result == 0: print(f"Enabled device: {device.PNPDeviceID}") else: print(f"Failed to enable device: Error code {result}") except Exception as e: print(f"Failed to enable device: {e}") 禁用需要管理员权限,怎么添加管理员权限运行命令
最新发布
03-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值