鸿蒙next 读取 rawFile 中的json 并转换成对象

169 阅读1分钟

1 json 文件放置位置

image.png

2 读取内容

const resourceManager = getContext().resourceManager;
const res = await resourceManager.getRawFileContent('mockFriendMomentOneModelData.json');

3 解析内容

interface MyJsonModel {
  friendMoments: FriendMoment[];
}

const textDecoder = util.TextDecoder.create();
const friendMomentArray = (JSON.parse(textDecoder.decodeWithStream(res)) as MyJsonModel).friendMoments;
export class FriendMoment {
  id: string;
  userName: string;
  avatar: string;
  text: string;
  image?: string;

  constructor(id: string, userName: string, avatar: string, text: string, image?: string) {
    this.id = id;
    this.userName = userName;
    this.avatar = avatar;
    this.text = text;
    if (image !== undefined) {
      this.image = image;
    }
  }
}