HarmonyOS 鸿蒙Next 从本地下载json文件存入沙箱后读取出来使用json解析报错,但json.cn在线解析正常
使用下载功能下载到沙箱,再读取出来,json解析时报错:Unexpected Text in JSON。
但是把得到的文本拿到json.cn是可以正常格式化的,
另外,这个json文件放在raw文件夹里读取,可以正常解析,很奇怪
帮忙看下下载后读取这块我的逻辑有什么问题吗?为什么会解析失败,感谢。
down(context: Context, url: string, fileName: string, outFilePath: string, isJson:boolean, success:(json:string)=>void) {
let filesDir = context.filesDir;
let filePath = filesDir + fileName
request.downloadFile(context, {
url: url,
filePath: filePath,
}).then((downloadTask: request.DownloadTask) => {
downloadTask.on('complete', () => {
AppLog.info('download complete fileName : ' + fileName)
// fs.copyFileSync(filePath, outFilePath)
//读取
if(isJson){
let result = ResUtils.readFileContent(context, fileName)
success(result)
}else{
success('')
}
})
downloadTask.on('progress', (uploadedSize: number, totalSize: number) => {
AppLog.info('progress >> ' + 'uploadedSize : ' + uploadedSize + ' ; totalSize :' + totalSize)
})
downloadTask.on('fail', (err: number) => {
AppLog.info('download fail >> ' + 'err : ' + err)
})
})
}
//读取方法
readFileContent(context: Context, fileName: string):string{
let filesDir:string = context.filesDir;
let filePath = filesDir + fileName
let file:fs.File = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
let readSize = 0
let arrayBuffer = new ArrayBuffer(4096);
let readAll = 0
while(true){
let currSize = fs.readSync(file.fd, arrayBuffer, {offset:readSize, length:4096} )
if(currSize < 4096){
break
}
readAll += currSize
}
fs.closeSync(file);
let result = buffer.from(arrayBuffer).toString('utf-8')
AppLog.info('readResult : ' + result)
return result
}
getRaw(path:string){
let unit8Array = getContext().resourceManager.getRawFileContentSync(path);
let json = ChangeHelper.uint8ArrayToStr(unit8Array);
AppLog.info('res json = ' + json);
return json;
}
uint8ArrayToStr(uint8Array:Uint8Array):string{
let str:string = buffer.from(uint8Array.buffer).toString('utf-8');
return str;
}
实体类:
export class CoursePlayStepBean {
ratings: Ratings[] = []
steps: Steps[] = []
branchs: BranchStep[] = []
videoCall: string = ''
}
export class BranchStep {
id: string = ''
name: string = ''
image: string = ''
liveUrl: string = ''
steps: Steps[] = []
}
export class Steps {
scene: string = ''
scale: string = ''
audio: string = ''
video: string = ''
image: string = ''
branch: number = 0
tag: string = ''
}
export class Ratings {
lottie: string = ''
sounds: string[] = []
star: number = 0
bgcolor: Bgcolor = new Bgcolor()
}
export class Bgcolor {
color: string = ''
opacity: number = 0
fade_time: number = 0
}
更多关于HarmonyOS 鸿蒙Next 从本地下载json文件存入沙箱后读取出来使用json解析报错,但json.cn在线解析正常的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
可以看一下class-transformer三方库,可以实现string转成对象:
可以参考这个demo:
import request from '@ohos.request';
import picker from '@ohos.file.picker';
import fs, { ReadOptions } from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import { buffer } from '@kit.ArkTS';
import { plainToClass } from "class-transformer";
// 获取应用文件路径
let context = getContext(this) ;
let message = ''
function down(context: Context, url: string, fileName: string, outFilePath: string, isJson:boolean) {
let filesDir = context.filesDir;
let filePath = filesDir + fileName
request.downloadFile(context, {
url: url,
filePath: filePath,
}).then((downloadTask: request.DownloadTask) => {
downloadTask.on('complete', () => {
console.info('download complete fileName : ' + fileName)
// fs.copyFileSync(filePath, outFilePath)
//读取
if(isJson){
let result =readFileContent(context, fileName)
console.log(result);
message =result
}else{
console.log('1');
}
})
downloadTask.on('progress', (uploadedSize: number, totalSize: number) => {
console.info('progress >> ' + 'uploadedSize : ' + uploadedSize + ' ; totalSize :' + totalSize)
})
downloadTask.on('fail', (err: number) => {
console.info('download fail >> ' + 'err : ' + err)
})
})
}
export class CoursePlayStepBean {
ratings: Ratings[] = []
steps: Steps[] = []
branchs: BranchStep[] = []
videoCall: string = ''
}
export class BranchStep {
id: string = ''
name: string = ''
image: string = ''
liveUrl: string = ''
steps: Steps[] = []
}
export class Steps {
scene: string = ''
scale: string = ''
audio: string = ''
video: string = ''
image: string = ''
branch: number = 0
tag: string = ''
}
export class Ratings {
lottie: string = ''
sounds: string[] = []
star: number = 0
bgcolor: Bgcolor = new Bgcolor()
}
export class Bgcolor {
color: string = ''
opacity: number = 0
fade_time: number = 0
}
function readFileContent(context: Context, fileName: string):string{
let filesDir:string = context.filesDir;
let filePath = filesDir + fileName
let file:fs.File = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
let readSize = 0
let arrayBuffer = new ArrayBuffer(4096);
let readAll = 0
while(true){
let currSize = fs.readSync(file.fd, arrayBuffer, {offset:readSize, length:4096} )
if(currSize < 4096){
break
}
readAll += currSize
}
fs.closeSync(file);
let result = buffer.from(arrayBuffer).toString('utf-8')
console.info('readResult : ' + result)
return result
}
@Entry
@Component
struct Index4 {
@State message:string ='test'
@State coursePlayStepBean:CoursePlayStepBean|undefined = undefined
build() {
Column(){
Button('test').onClick((event: ClickEvent) => {
down(context,'json','content.json','',true)
})
Text(this.message)
.onClick(()=>{
this.message = message
try {
this.coursePlayStepBean = plainToClass(CoursePlayStepBean, message)
}
catch (Error){
}
console.log('testsuccess'+JSON.stringify(this.coursePlayStepBean))
})
}
}
}
更多关于HarmonyOS 鸿蒙Next 从本地下载json文件存入沙箱后读取出来使用json解析报错,但json.cn在线解析正常的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
uint8ArrayToStr(uint8Array:Uint8Array):string{ let str:string = buffer.from(uint8Array.buffer).toString('utf-8'); return str; }
格式的问题吧?
针对您提到的HarmonyOS鸿蒙Next系统中从本地下载JSON文件存入沙箱后读取并解析报错的问题,可能的原因及解决方案如下:
-
文件编码问题:确保下载并存储的JSON文件编码为UTF-8,因为JSON解析器通常对编码格式敏感。
-
文件内容损坏:在下载和存储过程中,文件内容可能已损坏。请检查文件完整性,确保下载过程无误。
-
文件路径或权限问题:确认文件存储路径是否正确,以及应用是否有权限访问该路径。鸿蒙系统的沙箱机制对文件访问有严格限制。
-
解析器使用不当:检查您的JSON解析器使用方式是否正确,包括是否正确初始化、是否遵循了解析器的API规范等。
-
JSON格式错误:虽然在线解析正常,但本地解析报错可能源于本地JSON文件存在细微的格式错误,如多余的逗号、引号不匹配等。请仔细比对在线和本地JSON文件内容。
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html 。