HarmonyOS JSON转实体类?

现在支持json字符串转范型对象的API么

阅读 442
1 个回答

请参考:

@Observed class ArticleRes {
  code: number = -1
  data: Array<Article> = [] }
@Observed class Article {
  id: string;
  title: string;
  brief: string;
  isLiked: boolean;
  likesCount: number;
  constructor(id: string, title: string, brief: string, isLiked: boolean, likesCount: number) {
    this.id = id;
    this.title = title;
    this.brief = brief;
    this.isLiked = isLiked;
    this.likesCount = likesCount;
  }
}
res = `{""code"":0,""data"":[
  {""id"":""001"",""title"":""第0篇文章"",""brief"":""文章简介内容"",""isLiked"":false,""likesCount"":100},
  {""id"":""002"",""title"":""第1篇文章"",""brief"":""文章简介内容"",""isLiked"":false,""likesCount"":100},
  {""id"":""003"",""title"":""第2篇文章"",""brief"":""文章简介内容"",""isLiked"":false,""likesCount"":100},
  {""id"":""004"",""title"":""第4篇文章"",""brief"":""文章简介内容"",""isLiked"":false,""likesCount"":100},
  {""id"":""005"",""title"":""第5篇文章"",""brief"":""文章简介内容"",""isLiked"":false,""likesCount"":100},
  {""id"":""006"",""title"":""第6篇文章"",""brief"":""文章简介内容"",""isLiked"":false,""likesCount"":100}
  ]
  }`;

let articleRes: ArticleRes = JSON.parse(this.res)

也可以尝试使用第三方库:class-transformer,进行转换,请参考:

https://gitee.com/openharmony-tpc/openharmony\_tpc\_samples/tree/master/class-transformer

logo
HarmonyOS
子站问答
访问
宣传栏