HarmonyOS鸿蒙Next中解析json报错:The file content is empty.

HarmonyOS鸿蒙Next中解析json报错:The file content is empty.

代码如下:

import { util, buffer } from '@kit.ArkTS';

@Entry
@Component
struct JSONTestPage {
  private TAG: string = "JSONTestPage";
  @State showText: string = "";

  aboutToAppear(): void {
    this.getRawJson();
  }

  /**
   * 获取JSON
   */
  private getRawJson() {
    try {
      getContext().resourceManager.getRawFileContent("test.json").then((value: Uint8Array) => {
        console.log('value:', value);
        if (value.length === 0) {
          console.error("The file content is empty.");
          return;
        }
        let decoder = util.TextDecoder.create('utf-8');
        let json = decoder.decodeToString(value);
        console.info(this.TAG, "json: " + json);
        this.showText = json;
      }).catch((error: BusinessError) => {
        console.error("getRawFileContent promise error is " + JSON.stringify(error));
      });
    } catch (error) {
      let code = (error as BusinessError).code;
      let message = (error as BusinessError).message;
      console.error(`promise getRawFileContent failed, error code: ${code}, message: ${message}.`);
    }
  }

  build() {
    Scroll() {
      Row() {
        Text(this.showText)
          .fontSize(25)
          .fontWeight(FontWeight.Bold)
          .fontColor('#000')
      }
    }
    .height('100%')
    .width('100%')
  }
}

json文件:

{
  "name": "test",
  "age": 18,
  "sex": "boy"
}

报错结果: image


更多关于HarmonyOS鸿蒙Next中解析json报错:The file content is empty.的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

本人问题已解决 请看:https://juejin.cn/post/7488621104959373362

更多关于HarmonyOS鸿蒙Next中解析json报错:The file content is empty.的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中解析JSON时遇到“The file content is empty”报错,通常是因为读取的文件内容为空或文件路径不正确。首先,确保文件路径正确且文件存在。其次,检查文件内容是否为空。可以使用File类读取文件内容,并通过JSONObjectJSONArray进行解析。如果文件内容为空,解析时会抛出此异常。确保文件中有有效的JSON数据。如果文件路径和内容都正确,检查是否有权限访问该文件。

在HarmonyOS鸿蒙Next中解析JSON时遇到“The file content is empty”错误,通常是因为读取的文件内容为空或文件路径不正确。请检查以下步骤:

  1. 确认文件路径:确保文件路径正确,文件存在于指定位置。
  2. 检查文件内容:打开文件,确认其内容不为空且格式正确。
  3. 读取文件:使用FileReaderInputStream正确读取文件内容。
  4. 解析JSON:使用JSONObjectJSONArray解析读取到的内容。

示例代码:

String jsonStr = FileUtils.readFileToString(new File("path/to/file.json"), "UTF-8");
JSONObject jsonObject = new JSONObject(jsonStr);

如果问题依旧,请检查文件权限和编码格式。

回到顶部