有没有HarmonyOS鸿蒙Next中读取并使用json的方法
有没有HarmonyOS鸿蒙Next中读取并使用json的方法
loadCityData(): void {
try {
let context = getContext(this) as common.UIAbilityContext;
context.resourceManager.getRawFileContent("city.json", (error: BusinessError, value: Uint8Array) => {
if (error != null) {
console.error("error is " + error);
} else {
let rawFile = value;
let str = buffer.from(rawFile.buffer).toString();
// 添加类型检查和转换
const jsonData: TravelDataJson = JSON.parse(str);
if (jsonData.travel_cities) {
this.cityData = jsonData.travel_cities.map(city => {
const newCity = new City();
newCity.city_name = city.city_name || '';
newCity.location = city.location || '';
// 处理 weather 对象
if (city.weather) {
newCity.weather.temperature = city.weather.temperature || '';
newCity.weather.condition = city.weather.condition || '';
newCity.weather.humidity = city.weather.humidity || '';
newCity.weather.wind_speed = city.weather.wind_speed || '';
}
// 处理 attractions 数组
if (city.top_attractions) {
newCity.top_attractions = city.top_attractions.map(attr => {
const newAttr = new Attraction();
newAttr.name = attr.name || '';
newAttr.category = attr.category || '';
newAttr.rating = Number(attr.rating) || 0;
newAttr.entry_fee = attr.entry_fee || '';
return newAttr;
});
}
newCity.local_foods = city.local_foods || [];
newCity.accommodation = city.accommodation || [];
return newCity;
});
}
console.log("json:" + this.cityData[0]?.city_name);
}
});
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
console.error(`callback getRawFileContent failed, error code: ${code}, message: ${message}.`);
}
}
更多关于有没有HarmonyOS鸿蒙Next中读取并使用json的方法的实战教程也可以访问 https://www.itying.com/category-93-b0.html
getRawFileContent
获取resources/rawfile目录下对应的rawfile文件内容,异步回调成功后返回 Uint8Array 类型的值。
对于json文件的数据,可以下面的方法将 Uint8Array 转为json字符串。
最后使用 JSON.parse(jsonStr) 转为字面量对象。
function uint8ArrayToString(array: Uint8Array) {
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM: true
}
let decodeToStringOptions: util.DecodeToStringOptions = {
stream: false
}
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
let retStr = textDecoder.decodeToString(array, decodeToStringOptions);
return retStr;
}
更多关于有没有HarmonyOS鸿蒙Next中读取并使用json的方法的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next中,可以使用@ohos.util模块的JSON类来解析JSON字符串。例如,使用JSON.parse()方法将JSON字符串转换为对象,或使用JSON.stringify()将对象序列化为JSON字符串。此外,@ohos.file.fs模块可用于读取JSON文件,结合JSON.parse()进行解析。
在HarmonyOS Next中,读取并使用JSON文件的方法是正确的。你的代码展示了从rawfile目录读取city.json文件,并将其解析为结构化数据的完整流程。
主要步骤包括:
- 使用
getContext(this)获取UIAbility上下文。 - 通过
resourceManager.getRawFileContent异步读取JSON文件,得到Uint8Array原始数据。 - 使用
buffer.from().toString()将二进制数据转换为字符串。 - 使用
JSON.parse()将字符串解析为JavaScript对象。 - 进行类型检查和数据映射,将解析后的对象转换为应用内定义的
City等模型类实例。
这是一种标准且推荐的做法。为了确保代码健壮性,你已添加了错误处理(try-catch和回调错误判断)和属性空值检查(||操作符),这很好。
注意:请确保city.json文件已放置在项目的resources/rawfile目录下,这是getRawFileContent方法默认的查找路径。

