HarmonyOS鸿蒙Next开发者技术支持-从本地json文件中读取数据并解析

HarmonyOS鸿蒙Next开发者技术支持-从本地json文件中读取数据并解析 有时候咱们的数据可以自己mock;

自己创建json文件 放在 resources/rawfile/data.json 下,可以指读取并解析

cke_801.png

getDataFromJSON<SettingLevelItem>('MinePage-Setting-Level-Items.json', this).forEach(item => {
      this.settingLevelItems.push(new SettingLevelItem(item))
    });
export function getDataFromJSON<T>(rawFileName: string, component?: Object): T[] {
  let result: T[] = [];
  try {
    let value: Uint8Array = getContext(component).resourceManager.getRawFileContentSync(rawFileName);
    result = JSON.parse(bufferToString(value.buffer)) as T[];
  } catch (error) {
    let code = (error as BusinessError).code;
    let message = (error as BusinessError).message;
    console.error(`getRawFileContentSync failed, error code: ${code}, message: ${message}.`);
  }

  return result;
}

可直接解析为对象,在项目中使用


更多关于HarmonyOS鸿蒙Next开发者技术支持-从本地json文件中读取数据并解析的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS Next中,使用@ohos.file.fs@ohos.util模块实现本地JSON文件读取与解析。通过fs.openSyncfs.readSync读取文件内容,获取Uint8Array数据后转为字符串。使用util.parseJSON解析字符串为JS对象。注意文件路径需使用应用沙箱路径(如globalThis.fileDir),并提前在module.json5中声明文件访问权限。

更多关于HarmonyOS鸿蒙Next开发者技术支持-从本地json文件中读取数据并解析的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,通过resourceManager.getRawFileContentSync读取本地JSON文件并解析为对象是标准做法。代码示例中的getDataFromJSON函数封装了文件读取和JSON解析过程,利用泛型T直接返回目标类型的数组。需注意文件路径需放置在resources/rawfile/目录下,并确保JSON结构与目标类型匹配。异常处理已包含,可捕获文件读取或解析错误。此方法适用于本地静态数据加载场景。

回到顶部