【问题标题】:JSON.stringify not working for all properties of object in TypescriptJSON.stringify 不适用于 Typescript 中对象的所有属性
【发布时间】:2021-02-10 00:10:52
【问题描述】:

JSON.stringify 不适用于 Typescript 中最外层对象的所有属性。 请参考下面的代码sn-p:

class Criterion {
    '@CLASS' = 'xyz.abc.Criterion'
    operator: string;
    operand: string[];
    field: string;
    constructor(field:string,operator:string,operand: string[]) {
      this.field = field;
      this.operator = operator;
      this.operand = operand;
    }
}

class Filter {
    '@CLASS': 'xyz.ada.Filter';
    criteria: Criterion[];
    constructor(criteria:Criterion[]) {
        this.criteria=criteria;
    }
}

var criterion = new Criterion("a","b",["c"]);
var a = new Filter([criterion]);
JSON.stringify(a);
console.log(JSON.stringify(a));

输出:

{"criteria":[{"@CLASS":"xyz.abc.Criterion","field":"a","operator":"b","operand":["c"]}]}

预期:

{"@CLASS":"xyz.ada.Filter","criteria":[{"@CLASS":"xyz.abc.Criterion","field":"a","operator":"b","operand":["c"]}]}

它没有对 Filter 类对象的 @CLASS 属性进行字符串化。

code link

【问题讨论】:

    标签: json typescript stringify


    【解决方案1】:

    您的班级过滤器中有错字。将两个点替换为:

    '@CLASS'= 'xyz.ada.Filter';
    

    【讨论】:

      猜你喜欢
      • 2016-04-11
      • 2015-07-06
      • 2020-12-24
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 2013-04-16
      相关资源
      最近更新 更多