API12版本已推出关于JSON解析与生成的API方法,参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-json-V5可以使用ESObject,参考示例如下:import {JSON } from '@kit.ArkTS'; export interface commonRes { status: number returnJSON: ESObject; time: string } export interface returnRes { uid: string userType: number; } @Entry @Component struct Index { @State message: string = 'Hello World'; build() { RelativeContainer() { Text(this.message) .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(async (event: ClickEvent) => { // 将该json 解析成对象 let str = '{"returnJSON":{"uid":"02f17bc6b3fc465fab91d083844c7a29","userType":1,"createOn":"2024-07-12 16:38:18","thirdPartys":[],"info":{"cardNo":"AAA02342","radishQty":0},"showPage":false,"userMark":"old","isBlackNight":true,"installChannel":"Harmonyos","adChannel":"Harmonyos","showImg":"https://word.xxx.cn/tools/diary/UserDress/53c36b159ce84cf583db8f7d866cab40.png","IsDollOpen":true,"IsActivityOpen":true,"nickName":"匿名","level":1,"levelNick":"萌新","proType":0,"color":"#D2B7FF","PhotoFrameUrl":""},"status":1,"time":"2024-07-15 03:04:16"}' let str1 = '{"returnJSON":{"uid":"02f17bc6b3fc465fab91d083844c7a29","userType":1},"status":1,"time":"2024-07-15 03:04:16"}' let obj:commonRes = JSON.parse(str) as commonRes console.log("----1-time--"+obj.time) //方案一 自定义returnRes类 let res:returnRes = obj.returnJSON console.log("----1-uid-"+res.uid) //方案二 不定义returnRes类 let res1:ESObject = JSON.parse(JSON.stringify(obj.returnJSON)) console.log("----2-uid-"+res1["uid"]) }) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) } .height('100%') .width('100%') } }
API12版本已推出关于JSON解析与生成的API方法,参考链接:
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-json-V5
可以使用ESObject,参考示例如下: