HarmonyOS鸿蒙Next中json序列化 json解析 序列化反序列化丢失方法问题
HarmonyOS鸿蒙Next中json序列化 json解析 序列化反序列化丢失方法问题
1.安装插件
ohpm install class-transformer
ohpm install reflect-metadata
2.使用方法
p = plainToClass(Props,p)
import { JSON } from '@kit.ArkTS';
import { promptAction } from '@kit.ArkUI';
import { plainToClass } from 'class-transformer';
class Props {
public name: string;
public age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
toString(): string {
promptAction.showToast({
message: `name:${this.name},age:${this.age}`,
duration: 2000
});
return `name:${this.name},age:${this.age}`;
}
}
@Entry
@Component
struct StartCameraPickerView {
build() {
Column() {
Button("序列化反序列化")
.onClick(() => {
let props:Props = new Props("张三", 18);
let jsonData:string = JSON.stringify(props);
let p = JSON.parse(jsonData) as Props;
p = plainToClass(Props,p)
p.toString()
})
}
.width("100%")
.height("100%")
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
}
}
将Map转换为JSON字符串
let mapSource = new Map<string, string>();
mapSource.set('name', 'name1');
mapSource.set('width', '100');
mapSource.set('height', '50');
let jsonObject: Record<string, Object> = {};
mapSource.forEach((value, key) => {
if (key !== undefined && value !== undefined) {
jsonObject[key] = value;
}
})
let jsonInfo: string = JSON.stringify(jsonObject);
@Entry
@Component
struct Index {
build() {
Column() {
Button('Map to JSON')
.onClick(() => {
console.log('jsonInfo:', jsonInfo); // jsonInfo: {"name":"name1","width":"100","height":"50"}
})
}
}
}
json转Record
//json转object
let jsonRecord: Record<string, Object> = JSON.parse(info) as Record<string, Object>;
console.log("json转object:" + jsonRecord)
json转map
import { HashMap } from '@kit.ArkTS';
let str: string = '{"common_params": {' +
'"city_id": 1,' +
'"nav_id_list": "",' +
'"show_hook_card": 2,' +
'"use_one_stop_structure": 1,' +
'"version_tag": "homepageonestop"' +
'}' +
'}';
let jsonObj: Object = JSON.parse(str);
let commObj = (jsonObj as Record<string, Object>);
let commRecord = (commObj['common_params'] as Record<string, Object>);
let keyStr = Object.keys(commRecord);
for (let index: number = 0; index < keyStr.length; index++) {
commRecord[keyStr[index].toString()].toString();
}
let hashMapData: HashMap<string, Object> = new HashMap();
hashMapData.set('common_params', commRecord);
@Entry
@Component
struct Index {
build() {
Row() {
Column() {
Button('JSON to HashMap')
.onClick(() => {
// common_params: {"city_id":1,"nav_id_list":"","show_hook_card":2,"use_one_stop_structure":1,"version_tag":"homepageonestop"}
console.log('common_params:', JSON.stringify(hashMapData.get('common_params')));
})
}
.width('100%')
}
.height('100%')
}
}
json转部分属性
let jsonStr2 = JSON.stringify(obj, ['name']);
反序列化number类型丢失精度
https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-arkts-129-V5
import { JSON } from '@kit.ArkTS';
@Entry
@Component
struct Index {
@State str: string = 'bigint num';
build() {
Row() {
Column() {
Button(this.str)
.onClick(() => {
let numberText = '{"largeNumber":1122333444455556666677777888889}';
let numberObj = JSON.parse(numberText, undefined, {
bigIntMode: JSON.BigIntMode.PARSE_AS_BIGINT,
}) as Object;
let numberObj2 = JSON.parse(numberText) as Object;
console.info((numberObj as object)?.["largeNumber"]); // 1122333444455556666677777888889
console.info((numberObj2 as object)?.["largeNumber"]); // 1.1223334444555567e+30
})
}
.width('100%')
}
.height('100%')
}
}
更多关于HarmonyOS鸿蒙Next中json序列化 json解析 序列化反序列化丢失方法问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next中,JSON序列化与反序列化使用@ohos.util
提供的JSON类,通过parse()
和stringify()
方法实现。序列化过程仅处理可枚举属性,方法属于不可枚举内容,因此默认会丢失。若需保留方法逻辑,需在序列化前将方法转换为可序列化的数据形式(如字符串标识),并在反序列化后手动还原。系统未内置方法序列化支持。
更多关于HarmonyOS鸿蒙Next中json序列化 json解析 序列化反序列化丢失方法问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next中,JSON序列化和反序列化确实存在方法丢失的问题,这是因为JSON.stringify默认只序列化对象的属性,不包括方法。你提供的代码中使用了class-transformer的plainToClass方法,这是正确的解决方案。
具体来说:
- 使用plainToClass可以在反序列化时重新实例化类对象,恢复原型链上的方法
- 对于number精度问题,可以使用JSON.parse的bigIntMode选项来保持大数字的精度
- Map和Record的转换方案也是可行的
你的实现方式符合HarmonyOS Next的最佳实践,能够有效解决序列化过程中方法丢失的问题。