本文同步发表于微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新
一、JSON 处理方式
| 方式 | 包/模块 | 特点 | 适用场景 |
|---|
| 内置 JSON 对象 | 全局 JSON | 标准 Web API | 简单场景 |
核心方法
| 方法 | 语法 | 描述 | 参数 | 返回值 |
|---|
parse() | JSON.parse(text[, reviver]) | 解析 JSON 字符串 | text: 要解析的字符串 reviver: 可选转换函数 | 解析后的对象 |
stringify() | JSON.stringify(value[, replacer[, space]]) | 将值转换为 JSON 字符串 | value: 要转换的值 replacer: 可选过滤函数或数组 space: 可选缩进空格数或字符串 | JSON 字符串 |
二、使用介绍
1. JSON.parse() - 字符串转对象
// 基础用法
const jsonString = '{"name":"张x","age":66,"isStudent":true}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // 张x
console.log(obj.age); // 66
// 带 reviver 函数
const data = JSON.parse(jsonString, (key, value) => {
if (key === 'age') {
return value + 1; // 对特定字段进行处理
}
return value;
});
console.log(data.age); // 66
// 处理日期字符串
const jsonWithDate = '{"date":"2024-01-15T10:30:00.000Z"}';
const objWithDate = JSON.parse(jsonWithDate, (key, value) => {
if (key === 'date') {
return new Date(value);
}
return value;
});
console.log(objWithDate.date instanceof Date); // true
2. JSON.stringify() - 对象转字符串
const user = {
name: "李x",
age: 30,
city: "北京",
skills: ["TypeScript", "HarmonyOS"],
profile: {
level: "高级",
experience: 5
}
};
// 基础用法
const jsonStr = JSON.stringify(user);
console.log(jsonStr);
// {"name":"李x","age":30,"city":"北京","skills":["TypeScript","HarmonyOS"],"profile":{"level":"高级","experience":5}}
// 带 replacer 参数
const filteredStr = JSON.stringify(user, ["name", "age"]);
console.log(filteredStr); // {"name":"李x","age":30}
// 带 replacer 函数
const customStr = JSON.stringify(user, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});
console.log(customStr); // 所有字符串值转为大写
// 带缩进格式化
const prettyStr = JSON.stringify(user, null, 2);
console.log(prettyStr); // 格式化的 JSON 字符串
// 处理循环引用
const objA: any = { name: "A" };
const objB: any = { name: "B" };
objA.ref = objB;
objB.ref = objA;
try {
JSON.stringify(objA); // 报错:循环引用
} catch (e) {
console.error('循环引用错误:', e.message);
}
3. 实际应用
import { http } from '@kit.NetworkKit';
interface ApiResponse<T> {
code: number;
message: string;
data: T;
timestamp: number;
}
class ApiClient {
private baseUrl: string;
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
}
async get<T>(endpoint: string, params?: Record<string, any>): Promise<T> {
let url = `${this.baseUrl}${endpoint}`;
// 添加查询参数
if (params) {
const queryString = new URLSearchParams(params).toString();
url += `?${queryString}`;
}
let request = http.createHttp();
let response = await request.request(url, {
method: http.RequestMethod.GET,
header: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.responseCode === 200) {
const responseText = response.result.toString();
const apiResponse: ApiResponse<T> = JSON.parse(responseText);
if (apiResponse.code === 0) {
return apiResponse.data;
} else {
throw new Error(`API错误: ${apiResponse.message}`);
}
} else {
throw new Error(`HTTP错误: ${response.responseCode}`);
}
}
async post<T>(endpoint: string, data: any): Promise<T> {
let request = http.createHttp();
let response = await request.request(
`${this.baseUrl}${endpoint}`,
{
method: http.RequestMethod.POST,
header: {
'Content-Type': 'application/json'
},
extraData: JSON.stringify(data)
}
);
if (response.responseCode === 200) {
const responseText = response.result.toString();
return JSON.parse(responseText) as T;
} else {
throw new Error(`请求失败: ${response.responseCode}`);
}
}
}
// 使用示例
interface User {
id: number;
name: string;
email: string;
}
const apiClient = new ApiClient('https://api.example.com');
// 获取用户列表
async function getUsers(): Promise<User[]> {
return await apiClient.get<User[]>('/users');
}
// 创建新用户
async function createUser(userData: Partial<User>): Promise<User> {
return await apiClient.post<User>('/users', userData);
}