Read the original article:Reading Custom JSON Files in HarmonyOS Using getRawFileContent
Context
A developer is trying to read an intarray.json
resource defined in a HarmonyOS project. They initially attempted to use the getStringArrayValueSync
API from the ResourceManager
but found it ineffective for accessing raw JSON data.
Description
The developer encountered difficulties retrieving a custom intarray.json
file using typical resource manager methods intended for string or array resources. This file does not follow the standard element
resource format (e.g., string, string-array
) and thus requires a different approach for access and parsin
Solution / Approach
Instead of using getStringArrayValueSync, the correct method is:
- Place the intarray.json file into the resources/rawfile directory.
- Use the getRawFileContent() API from the ResourceManager to read its content as a Uint8Array.
- Convert the byte array into a string and parse it using JSON.parse().
Example Demo:
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { buffer, JSON } from '@kit.ArkTS';
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
private context = getContext(this) as common.Context;
aboutToAppear(): void {
try {
this.context.resourceManager.getRawFileContent('intarray.json')
.then((value: Uint8Array) => {
let strParam = buffer.from(value.buffer).toString()
let obj = JSON.parse(strParam) as Record<string, object>
let array = obj['intarray'] as Record<string, Array<number>>
Object.keys(array).forEach(key => {
if (array[key]['name'] == 'aaa') {
console.log(key, array[key]['value']);
}
});
console.log('Get Value:' + JSON.stringify(array))
})
.catch((error: BusinessError) => {
console.error("getRawFileContent promise error is " + 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() {
Column() {
Text(this.message)
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.height('100%')
.width('100%')
}
}
Key Takeaways
- Custom JSON files (like intarray.json) should be placed in resources/rawfile, not in element or string-array sections.
- getRawFileContent() is the correct API to read such files.
- Use buffer.from(...).toString() and JSON.parse() to convert and use the content.
- getStringArrayValueSync is intended for standard string-array resources and is not suitable for raw JSON parsing.
Additional Resources
https://developer.huawei.com/consumer/en/doc/harmonyos-guides/rawfile-guidelines
Top comments (0)