HarmonyOS json数据和对象互转时问题

创建一个类。

export class SchoolBean {
  id:number=0
  schoolName:string=""
  provinceName:string=""
  xzqhCode:string=""
}

实际使用如下:

let src = `{
"id":936,
"schoolName":"广州校",
"schoolDesc":"gz",
"defaultFlag":0,
"companyId":4,
"indexDomain":"",
"companyIdentification":"",
"xzqhCode":"440000",
"provinceName":"广东省"
}`

let tempSchool= JSON.parse(src ) as SchoolBean

为什么tempSchool对象中会存在defaultFlag、indexDomain等字段的值呢?比如只想在类对象中只包括声明的变量字段,如何实现呢?

HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

可以通过new对象来排除多余字段,参考代码如下:

import { JSON } from '@kit.ArkTS';

@Entry
@Component
struct Index3 {
  @State message: string = 'Hello World';
  aboutToAppear(): void {
    let src = `{
"id":936,
"schoolName":"广州校",
"schoolDesc":"gz",
"defaultFlag":0,
"companyId":4,
"indexDomain":"",
"companyIdentification":"",
"xzqhCode":"440000",
"provinceName":"广东省"
}`

    let param = JSON.parse(src) as SchoolBean
    let param2 = new SchoolBean(param)
    AlertDialog.show({ message: `${JSON.stringify(param2)}` })
  }

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('Index3HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
    }
    .height('100%')
    .width('100%')
  }
}

export class SchoolBean {
  constructor(param: SchoolBean) {
    this.id = param.id;
    this.schoolName = param.schoolName;
    this.provinceName = param.provinceName;
    this.xzqhCode = param.xzqhCode;
  }

  id: number = 0
  schoolName: string = ""
  provinceName: string = ""
  xzqhCode: string = ""
}
分享
微博
QQ
微信
回复
3天前
相关问题
如何打印JSON对象JSON字符串
411浏览 • 1回复 待解决
HarmonyOS 数据模型对象赋值问题
55浏览 • 1回复 待解决
HarmonyOS JSON对象失败
60浏览 • 1回复 待解决
HarmonyOS JSON对象转换
84浏览 • 1回复 待解决
HarmonyOS 如何创建json对象
506浏览 • 1回复 待解决
HarmonyOS map转json对象
42浏览 • 1回复 待解决
HarmonyOS http请求的JSON数据定义问题
261浏览 • 1回复 待解决
应用开发string.json问题
721浏览 • 1回复 待解决
HarmonyOS Long类型number的相互转
75浏览 • 1回复 待解决
HarmonyOS json对象转map类型
189浏览 • 1回复 待解决
pxvp之间如何相互转
2982浏览 • 1回复 待解决
HarmonyOSjson对象按照 ASCII 排序
540浏览 • 1回复 待解决
HarmonyOS json转换成对象
55浏览 • 2回复 待解决