JSON两层类的定义与实现:从基础到实践
在开发中,JSON(JavaScript Object Notation)作为一种轻量级的数据交换格式,因其易读性和灵活性被广泛应用,当处理结构较复杂的数据时(如嵌套的配置信息、API返回的层级数据),我们常常需要定义与JSON结构对应的“两层类”(即包含嵌套对象的类),以实现数据的序列化(对象转JSON)和反序列化(JSON转对象),本文将详细介绍JSON两层类的定义方法、实现逻辑及实际应用示例,帮助开发者这一常用技能。
理解“两层类”与JSON的对应关系
“两层类”通常指一个类中包含另一个类的对象作为属性,形成“外层类-嵌套类”的层级结构,一个“用户信息”JSON可能包含基本字段(如姓名、年龄)和一个“地址”对象(含省、市、街道),对应的类就是UserInfo(外层类)包含Address对象(嵌套类)。
要实现两层类的JSON处理,需满足以下核心逻辑:
- 属性与JSON字段一一对应:类的属性名需与JSON的key一致(或通过注解映射);
- 嵌套对象类型匹配:外层类的嵌套属性需声明为内层类的对象类型;
- 支持序列化与反序列化:需将对象转换为JSON字符串(序列化),或将JSON字符串解析为对象(反序列化)。
定义两层类的具体步骤
明确JSON结构,设计内层类和外层类
首先需分析目标JSON的结构,确定哪些字段属于外层类,哪些属于内层嵌套类,以一个“用户订单”JSON为例:
{
"orderId": "ORD001",
"customerName": "张三",
"orderDate": "2023-10-01",
"shippingAddress": {
"province": "广东省",
"city": "深圳市",
"detail": "南山区科技园"
},
"items": [
{
"productId": "P1001",
"productName": "笔记本电脑",
"quantity": 1,
"price": 5999.00
},
{
"productId": "P1002",
"productName": "鼠标",
"quantity": 2,
"price": 99.00
}
]
}
此JSON包含两层嵌套:
- 外层:订单基本信息(
orderId、customerName等)和嵌套的shippingAddress(地址对象)、items(商品列表,列表内每个元素是商品对象); - 内层:
ShippingAddress(地址类)、OrderItem(商品类)。
使用Java定义两层类(以常见语言为例)
(1)定义内层类(ShippingAddress和OrderItem)
内层类是外层类属性的“子结构”,需包含JSON中嵌套对象的字段。
// 内层类1:收货地址
public class ShippingAddress {
private String province;
private String city;
private String detail;
// 无参构造器(反序列化时需要)
public ShippingAddress() {}
// 全参构造器(方便对象创建)
public ShippingAddress(String province, String city, String detail) {
this.province = province;
this.city = city;
this.detail = detail;
}
// Getter和Setter(序列化/反序列化时通过反射访问字段)
public String getProvince() { return province; }
public void setProvince(String province) { this.province = province; }
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
public String getDetail() { return detail; }
public void setDetail(String detail) { this.detail = detail; }
// 可选:toString方法(便于调试)
@Override
public String toString() {
return "ShippingAddress{" +
"province='" + province + '\'' +
", city='" + city + '\'' +
", detail='" + detail + '\'' +
'}';
}
}
// 内层类2:订单商品
public class OrderItem {
private String productId;
private String productName;
private int quantity;
private double price;
// 无参构造器
public OrderItem() {}
// 全参构造器
public OrderItem(String productId, String productName, int quantity, double price) {
this.productId = productId;
this.productName = productName;
this.quantity = quantity;
this.price = price;
}
// Getter和Setter
public String getProductId() { return productId; }
public void setProductId(String productId) { this.productId = productId; }
public String getProductName() { return productName; }
public void setProductName(String productName) { this.productName = productName; }
public int getQuantity() { return quantity; }
public void setQuantity(int quantity) { this.quantity = quantity; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
@Override
public String toString() {
return "OrderItem{" +
"productId='" + productId + '\'' +
", productName='" + productName + '\'' +
", quantity=" + quantity +
", price=" + price +
'}';
}
}
(2)定义外层类(Order)
外层类包含基本类型属性和内层类对象属性,以及内层类列表(如items)。
import java.util.List; // 需要导入List接口
// 外层类:订单
public class Order {
private String orderId;
private String customerName;
private String orderDate;
private ShippingAddress shippingAddress; // 内层类对象(一层嵌套)
private List<OrderItem> items; // 内层类列表(二层嵌套,列表元素是内层对象)
// 无参构造器
public Order() {}
// 全参构造器
public Order(String orderId, String customerName, String orderDate,
ShippingAddress shippingAddress, List<OrderItem> items) {
this.orderId = orderId;
this.customerName = customerName;
this.orderDate = orderDate;
this.shippingAddress = shippingAddress;
this.items = items;
}
// Getter和Setter
public String getOrderId() { return orderId; }
public void setOrderId(String orderId) { this.orderId = orderId; }
public String getCustomerName() { return customerName; }
public void setCustomerName(String customerName) { this.customerName = customerName; }
public String getOrderDate() { return orderDate; }
public void setOrderDate(String orderDate) { this.orderDate = orderDate; }
public ShippingAddress getShippingAddress() { return shippingAddress; }
public void setShippingAddress(ShippingAddress shippingAddress) {
this.shippingAddress = shippingAddress;
}
public List<OrderItem> getItems() { return items; }
public void setItems(List<OrderItem> items) { this.items = items; }
@Override
public String toString() {
return "Order{" +
"orderId='" + orderId + '\'' +
", customerName='" + customerName + '\'' +
", orderDate='" + orderDate + '\'' +
", shippingAddress=" + shippingAddress +
", items=" + items +
'}';
}
}
处理JSON序列化与反序列化
定义好两层类后,需通过工具库实现对象与JSON的转换,以Java为例,常用工具库有Gson(Google)、Jackson、Fastjson(阿里巴巴)等,本文以Gson为例说明。
(1)添加依赖(Maven项目)
若使用Gson,需在pom.xml中添加依赖:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version> <!-- 使用最新稳定版本 -->
</dependency>
(2)实现序列化(对象→JSON字符串)
将Order对象转换为JSON字符串:
import com.google.gson.Gson;
public class JsonSerializationExample {
public static void main(String[] args) {
// 1. 创建内层对象
ShippingAddress address = new ShippingAddress("广东省", "深圳市", "南山区科技园");
// 2. 创建内层列表(OrderItem列表)
List<OrderItem> items = List.of(
new OrderItem("P1001", "笔记本电脑", 1, 5999.00),
new OrderItem("P1002", "鼠标", 2, 99.00)
);
// 3. 创建外层对象(Order)
Order order = new Order("ORD001", "张三", "2023-10-01", address, items);
// 4. 使用Gson进行序列化
Gson gson = new Gson();
String jsonString = gson.toJson(order);
// 输出JSON字符串
System.out


还没有评论,来说两句吧...