HarmonyOS class-transformer问题

class-transformer放到子线程处理。

HarmonyOS
2024-10-12 10:36:33
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zbw_apple

该问题可以参考开发指南(代码)实现。参考一demo:

data.ets

import { merge, ICreator } from './Merge'  
import { collections } from '@kit.ArkTS'  
'use shared'  
@Sendable  
export class Car {  
  name?: string;  
  myCarFunc() {  
    console.log('this is my CarFunc');  
  }  
}  
@Sendable  
export class CarCreator implements ICreator<Car> {  
  static field: collections.Set<string> = new collections.Set(['name']);  
  create(jsonObj: object): Car {  
    let ans: Car = new Car();  
    merge(ans, jsonObj, CarCreator.field);  
    return ans;  
  }  
  static instance: CarCreator = new CarCreator();  
  static getInstance(): CarCreator {  
    return CarCreator.instance;  
  }  
}  
@Sendable  
export class User {  
    id?: number;  
    firstName?: string;  
    lastName?: string;  
    car?: Car;  
    myUserFunc() {  
    console.log("this is my UserFunc");  
  }  
}  
@Sendable  
export class UserCreator implements ICreator<User> {  
    static field:collections.Set<string> = new collections.Set(['id', 'firstName', 'lastName']);  
  
    create(jsonObj:object): User {  
        let ans: User = new User();  
        merge(ans, jsonObj, UserCreator.field);  
        if (jsonObj['car']) {  
            ans.car = CarCreator.getInstance().create(jsonObj['car']);  
        }  
        return ans;  
    }  
    static instance:UserCreator = new UserCreator();  
    static getInstance() : UserCreator {  
        return UserCreator.instance;  
    }  
}

TaskPoolDeme.ets

import "reflect-metadata"  
import { User, UserCreator } from '../common/data'  
import { ICreator} from '../common/Merge'  
import { UserOrigin } from '../common/data_raw'  
import { plainUser } from '../common/JsonData'  
import { taskpool } from '@kit.ArkTS'  
import lang from '@arkts.lang';  
import { ClassConstructor, plainToClass } from 'class-transformer'  
// 只需要网路模块添加一个可序列化的函数, 预期写法  
@Concurrent  
 async function NetWorkServicetransformFunc<T extends lang.ISendable>(creator: ICreator<T>, plainData: Object): Promise<T> {  
   let plainClassObject = creator.create(plainData);  
   return plainClassObject as T;  
 }  
// 这是网络模块的类,所有模块的调用该模块的单例做网络等相关的操作  
class NetWorkService {  
  private static service: NetWorkService;  
  public static getInstance(): NetWorkService {  
    if (NetWorkService.service === undefined) {  
      NetWorkService.service = new NetWorkService();  
    }  
    return NetWorkService.service;  
  }  
  // .....  
  // 这里是做网路数据请求  
  async request<T>(dataType: ClassConstructor<T>, plainData: Object): Promise<T> { //各个模块都公用的接口  
    //网路请求:  
    //解析:  
    // 原始调用,使用plainToClass做数据转换,但是耗时比较严重,需要用taskpool执行耗时操作  
    let result = plainToClass(dataType, plainData, { excludeExtraneousValues: true })  
    return result as T;  
  }  
  async requestNew<T extends lang.ISendable>(creator: ICreator<T>, plainData: Object):Promise<T> {  
    let task:taskpool.Task = new taskpool.Task(NetWorkServicetransformFunc, creator, plainData);  
    return taskpool.execute(task, taskpool.Priority.HIGH).then((value:lang.ISendable) => value as T );  
  }  
}  
@Entry  
@Component  
struct TaskPoolDemo {  
  @State value: User = new User();  
  @State valueTS: User = new User();  
  @State valueOrigin: UserOrigin = new UserOrigin();  
  netWorkService: NetWorkService = NetWorkService.getInstance();  
  aboutToAppear() {  
  }  
  build() {  
    Row() {  
      Column() {  
        Text(`${JSON.stringify(plainUser)}`)  
        Button('class-transformer解析')  
          .onClick(async () => {  
             this.valueOrigin = await this.netWorkService.request(UserOrigin, plainUser);  
          })  
        Text(`class-transformer: ${JSON.stringify(this.valueOrigin)}`)  
        Button('from ets taskpool')  
          .onClick(async () => {  
            this.value =  await this.netWorkService.requestNew(UserCreator.getInstance(), plainUser);  
          })  
        Text(`from ets: ${JSON.stringify(this.value)}`)  
      }  
      .width('100%')  
    }  
    .height('100%')  
  }  
}

Merge.ets(该文件是通过转换工具生成的)

export function merge(target, source, keys) {  
  if (!source) {  
    return;  
  }  
  for (const key in source) {  
    if (keys.has(key)) {  
      Object.assign(target, { [key]: source[key] });  
    }  
  }  
}  
export interface ICreator<T> {  
  create(jsonObj: object): T;  
}

data_raw.ts,这是原始要转换的类的定义文件。

import { Expose, Type } from 'class-transformer'  
export class Car {  
  @Expose() name: string  
  myCarFunc() {  
    console.log("this is my CarFunc");  
  }  
}  
export class UserOrigin {  
  @Expose() id: number;  
  @Expose() firstName: string;  
  @Expose() lastName: string;  
  @Type(() => Car)  
  @Expose() car: Car;  
  myUserFunc() {  
    console.log("this is my UserFunc");  
  }  
}  
// 期望输出  
//  
// {"lastName":"yongzi","car":{"name":"BMW"}}  
JsonData.ts 这是字面量数据,用于模拟网络请求下来的数据  
export const plainUser = {  
  unknowProp: 'hello there',  
  lastName:'yongzi',  
  car:{  
    name:'BMW',  
    brand:'X1'  
  }  
}
分享
微博
QQ
微信
回复
2024-10-12 17:03:23
相关问题
HarmonyOS 嵌套Class状态观察问题
49浏览 • 1回复 待解决
HarmonyOS class 转 Map
214浏览 • 1回复 待解决
求js 中 class类名动态绑定的问题
6460浏览 • 1回复 待解决
HarmonyOS 获取class实例上的所有函数名
467浏览 • 1回复 待解决
NAPI中定义并注册Class
736浏览 • 1回复 待解决
class二次刷新渲染数组
744浏览 • 1回复 待解决
HarmonyOS class中创建对话框不能显示
45浏览 • 1回复 待解决
napi常见用法:class对象绑定
1147浏览 • 1回复 待解决