JSON 对象封装教程

JSON 对象封装方法

在 Java 中封装 JSON 对象通常使用第三方库,如 org.jsonGsonJackson。以下是几种常见的方法:

使用 org.json 库

添加 Maven 依赖:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20231013</version>
</dependency>

创建和封装 JSON 对象:

import org.json.JSONObject;

JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John");
jsonObject.put("age", 30);
jsonObject.put("isStudent", false);

String jsonString = jsonObject.toString();

使用 Gson 库

添加 Maven 依赖:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

通过对象转换:

import com.google.gson.Gson;

class Person {
    String name = "John";
    int age = 30;
    boolean isStudent = false;
}

Gson gson = new Gson();
String json = gson.toJson(new Person());

手动构建:

import com.google.gson.JsonObject;

JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", "John");
jsonObject.addProperty("age", 30);
jsonObject.addProperty("isStudent", false);

String jsonString = jsonObject.toString();

使用 Jackson 库

添加 Maven 依赖:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>

通过对象转换:

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(new Person());

手动构建:

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.JsonNodeFactory;

ObjectNode node = JsonNodeFactory.instance.objectNode();
node.put("name", "John");
node.put("age", 30);
node.put("isStudent", false);

String jsonString = node.toString();

性能比较

  • org.json:轻量级,适合简单场景
  • Gson:Google 出品,易用性高
  • Jackson:性能最优,功能最强大

复杂对象封装

对于嵌套对象或列表:

// Gson 示例
class Address {
    String city;
    String street;
}

class User {
    String name;
    List<Address> addresses;
}

User user = new User();
// 设置属性...

Gson gson = new Gson();
String json = gson.toJson(user);

注意事项

  • 处理日期时需要自定义序列化/反序列化
  • 循环引用会导致栈溢出,需特别处理
  • 大量数据时考虑流式 API(如 Jackson 的 JsonGenerator)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值