创建json对象

本文详细介绍使用Alibaba FastJSON库在Java中创建复杂JSON对象的方法,包括基本属性设置、集合处理、对象嵌套及异常捕获,为开发者提供实用的代码示例。

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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

public class CreateJsonObjTest {
	private static void toJson() {
		JSONObject jsonObject = new JSONObject();
		try {
			//形式1 普通
			jsonObject.put("a", "a_value");
			jsonObject.put("b", "b_value");
			//形式2 集合
			JSONArray json_c = new JSONArray();
			json_c.add("c1_value");
			json_c.add("c2_value");
			jsonObject.put("c", json_c);
			//形式3 对象
			JSONObject json_d = new JSONObject();
			json_d.put("d1", "d1_value");
			json_d.put("d2", "d2_value");
			jsonObject.put("d", json_d);
			//形式4 集合中嵌套对象
			JSONArray json_e = new JSONArray();
			JSONObject childer_1 = new JSONObject();
			childer_1.put("e1", "e1_value");
			childer_1.put("e2", "e2_value");
			json_e.add(childer_1);
			JSONObject childer_2 = new JSONObject();
			childer_2.put("e3", "e3_value");
			childer_2.put("e4", "e4_value");
			json_e.add(childer_2);
			jsonObject.put("e", json_e);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		System.out.println(jsonObject.toString());
		
	}
public static void main(String[] args) {
	long befor = System.currentTimeMillis();
	toJson();
	long now = System.currentTimeMillis();
	System.out.println(now-befor);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值