HarmonyOS class-transformer expose注解嵌套对象失效

代码:

import { classToPlain, Expose, plainToClass } from 'class-transformer';
import 'reflect-metadata';
class MyClass {
  @Expose({ name: 'auth-type' })
  authType: number = 1;
  meta: AuthorMeta = new AuthorMeta();
}
class AuthorMeta {
  @Expose({ name: 'focus_count' })
  focusCount: number = 0;
}

let result = plainToClass(MyClass, JSON.parse("{\"auth-type\":3,\"meta\":{\"focus_count\":333} }"))
console.log("focus_countis "+result.meta.focusCount);

打印结果:focusCount is undefined。

HarmonyOS
7天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
aquaa

对于嵌套的场景,需要将嵌套的类再次通过plainToClass进行转换,如下:

参考代码:

import { classToPlain, Expose, plainToClass } from 'class-transformer';
import 'reflect-metadata';

@Entry
@Component
struct Test6 {
  build() {
    Column(){
      Button('验证1').onClick((event: ClickEvent) => {
        let myClass: MyClass = new MyClass();
        myClass.authType = 1;
        let serializedData = classToPlain(myClass);
        let jsonStr: string = JSON.stringify(serializedData)
        console.log(jsonStr);
        let myClass1: MyClass = JSON.parse(jsonStr)
        let myDataObject = plainToClass(MyClass, myClass1);
        console.log("authType is " + myDataObject.authType);
        let myAuthMeta = plainToClass(AuthorMeta, myDataObject.meta)
        console.log("focusCount is " + myAuthMeta.focusCount);
      })
      Button('验证2').onClick((event: ClickEvent) => {
        let result = plainToClass(MyClass, JSON.parse("{\"auth-type\":3,\"meta\":{\"focus_count\":333}}"))
        let result1 = plainToClass(AuthorMeta, result.meta)
        console.log("focusCount is "+result1.focusCount);
      })
    }
  }
}

class MyClass {
  @Expose({ name: 'auth-type' })
  authType: number = 1;
  meta: AuthorMeta = new AuthorMeta();
}

class AuthorMeta {
  @Expose({ name: 'focus_count' })
  focusCount: number = 0;
}
分享
微博
QQ
微信
回复
7天前
相关问题
HarmonyOS class-transformer问题
712浏览 • 1回复 待解决
RelativeContainer布局嵌套Stack失效
440浏览 • 1回复 待解决
HarmonyOS 嵌套Class状态观察问题
120浏览 • 1回复 待解决
napi常见用法:class对象绑定
1206浏览 • 1回复 待解决
嵌套Class的属性变化无法触发UI渲染
416浏览 • 1回复 待解决
如何将JSON字符串转Class对象
559浏览 • 1回复 待解决
HarmonyOS 注解功能
128浏览 • 1回复 待解决