java使用org.json解析josn字符串与json文件

本文详细介绍了如何使用org.json库在Eclipse环境中操作JSON数据,包括导入jar包、创建和解析JSON字符串及文件,提供了完整的代码示例。

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

准备org.json.jar

一、最近做项目需要操作json,趁着这次机会就好好总结一下。本次使用的是org.json提供的jar包,下载地址为mvnrepository(jar包仓库,开发所需的jar包都可以在上面下载)。

二、在eclipse上导入外部jar文件,方法:选中项目右击 -> Build Path -> Configure Build Path -> 选择Libraries -> 点击Add JARs… -> 选择下载的jar包,点击“OK”并应用

 创建Json字符串与test.json文件

创建要操作的json字符串:

String jsonStr = "{\"name\":\"小明\",\"information\":{\"sex\":\"man\",\"hobby\":\"sing\"},\"pwd\":\"666\",\"parents\":[{\"father\":\"大明\",\"job\":\"farmer\"},{\"mother\":\"明\",\"job\":\"engineer\"}]}";

创建test.json文件,文件内容为:

{
	"name":"小红",
	"pwd":"123",
	"information":{
		"sex":"woman",
		"hobby":"swim"
	},"parents":[
	   {
		   "father:":"大红",
		   "job":"coder"
	   },{
		   "mother":"红",
		   "job":"engineer"
	   }
	]
}

正式解析



import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

public class Test {
	public static void main(String[] args) throws IOException {
		String jsonStr = "{\"name\":\"小明\",\"information\":{\"sex\":\"man\",\"hobby\":\"sing\"},\"pwd\":\"666\",\"parents\":[{\"father\":\"大明\",\"job\":\"farmer\"},{\"mother\":\"明\",\"job\":\"engineer\"}]}";
		//将整个json字符串转换成JSONObject对象
		JSONObject jo = new JSONObject(jsonStr);
		System.out.println("jsonStr:"+jo.toString());
		System.out.println("name:"+jo.getString("name")+" pwd:"+jo.getString("pwd"));
		//读取json中的对象
		JSONObject jo1 = jo.getJSONObject("information");
		System.out.println("information:"+jo1.toString());
		System.out.println("sex:"+jo1.getString("sex")+" hobby:"+jo1.getString("hobby"));
		//读取json中的数组
		JSONArray ja = jo.getJSONArray("parents");
		System.out.println(ja.toString());
		JSONObject jo1_father = ja.getJSONObject(0);
		System.out.println("father:"+jo1_father.getString("father")+" job:"+jo1_father.getString("job"));
		JSONObject jo1_mother = ja.getJSONObject(1);
		System.out.println("mother:"+jo1_mother.getString("mother")+" job:"+jo1_mother.getString("job"));
		
		//读取json文件
		//方法一:按照上面操作json字符串的原理,我们可以先将json文件转换成字符串在进行操作(注意填写正确的文件路径)
		FileReader fr = new FileReader(new File("file/test.json"));
		BufferedReader br = new BufferedReader(fr);
		String fileStr ="";
		String tempStr = br.readLine();
		while(tempStr!=null) {
			fileStr += tempStr;
			tempStr = br.readLine();
		}
		//生成JSONObject对象,后续操作上面相同
		JSONObject jo2 = new JSONObject(fileStr);
		System.out.println("jsonFile:"+jo2.toString());
		
		//方法二:使用JSONTokener读取json文件,之后转换为JSONObject对象,后续操作与上面相同(注意填写正确的文件路径)
		JSONTokener jt = new JSONTokener(new FileReader(new File("file/test.json")));
		JSONObject jo3 = (JSONObject)jt.nextValue();
		System.out.println("jsonFile:"+jo3.toString());
		
	}
}

 

MQTT(Message Queuing Telemetry Transport)是一种轻量级的发布/订阅消息协议,主要用于物联网(IoT)设备之间的通信。在C#中,你可以使用各种库来处理MQTT,如Mosquitto.Net、Stact.MQTT等,它们通常包含JSON支持。 如果你想要使用MQTTX (假设它是一个MQTT客户端库),发送一个JSON字符串,可以按照以下步骤操作: 1. 首先,安装MQTTX客户端库,比如通过NuGet包管理器添加`Mqttnet`或`mqttxlabs-mqttnetclient`。 ```csharp Install-Package Mqttnet ``` 2. 创建一个MQTT连接,并设置主题(topic)来接收数据。 ```csharp using MqttNet; // ... var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); await mqttClient.ConnectAsync(new MqttConnectOptions { ServerUri = "tcp://your_mqtt_broker.com:1883", // 替换为你的MQTT服务器地址 CleanSession = true, }); ``` 3. 定义一个JSON字符串并将其编码为字节序列,因为MQTT通常传输的是字节数据。 ```csharp string jsonString = "{\"key\":\"value\"}"; // JSON数据 byte[] jsonDataBytes = Encoding.UTF8.GetBytes(jsonString); ``` 4. 使用`PublishAsync`方法发送JSON数据到指定的主题。 ```csharp await mqttClient.PublishAsync("your/topic", jsonDataBytes, QualityOfService.AtLeastOnce); ``` 5. 接收者可以在订阅了该主题的客户端上解析接收到的数据,例如使用Json.NET库(`System.Text.Json`或`Newtonsoft.Json`)来解码字节数组JSON。 ```csharp var jsonStringReceived = Encoding.UTF8.GetString(jsonDataBytes); var jsonObject = JsonConvert.DeserializeObject<YourJsonObjectType>(jsonStringReceived); // 替换为你的实际JSON对象类型 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值