将带符号的ES6类转换为JSON

Jon*_*lis 7 javascript json ecmascript-6 aurelia

我有硬编码的类来表示我的Aurelia应用程序中的模型.这是一个'PostEdit'模型:

var _postID = Symbol();
var _title = Symbol();
var _text = Symbol();

export class PostEdit {

    constructor(postEdit) {
        this[_postID] = postEdit.postID;
        this.title = postEdit.title;
        this.text= postEdit.text;
    }

    get postID() { return this[_postID]; }

    get title() { return this[_title]; }
    set title(val) { this[_title] = val; }

    get text() { return this[_text]; }
    set text(val) { this[_text] = val; }

}
Run Code Online (Sandbox Code Playgroud)

该对象被操纵后,我需要PUTPOST它回服务器.但它看起来像AureliaHttpClient是发送一个空JSON字符串({}).在研究它时,似乎Symbols在将ES6类转换为时忽略了JSON.

如何将所有属性都转换为JSON字符串以提交回服务器?

Tha*_*you 19

我假设您使用符号来保持数据私有,但这意味着如果您希望JSON表示中包含这些数据,您将不得不经历一些额外的步骤.

这是一个使用toJSON模型显式导出您关注的属性的示例

export class PostEdit {

  // ...
  toJSON() {
    return {
      postID: this.postID,
      title:  this.title,
      text:   this.text
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

要么

export class PostEdit {

  // ...
  toJSON() {
    let {postID, title, text} = this;
    return {postID, title, text};
  }
}
Run Code Online (Sandbox Code Playgroud)

JSON.stringify被调用您的实例,它会自动调用toJSON


Far*_*uti 8

要获得更多动态解决方案,请使用以下命令:

export class MeMe(){
 toJSON() {
    return Object.getOwnPropertyNames(this).reduce((a, b) => {
      a[b] = this[b];
      return a;
    }, {});
  }
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用我的json-decorator :)

import json from "json-decorator";  

@json("postID") // pass the property names that you want to ignore
export class MeMe(){
  // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 优雅的解决方案。 (2认同)

Ber*_*rgi 6

为您的类提供一个toJSON返回stringifyable对象的方法:

export class PostEdit {

    constructor(postEdit) {
        this[_postID] = postEdit.postID;
        this.title = postEdit.title;
        this.text = postEdit.text;
    }

    get postID() { return this[_postID]; }

    get title() { return this[_title]; }
    set title(val) { this[_title] = val; }

    get text() { return this[_text]; }
    set text(val) { this[_text] = val; }

    toJSON() {
        return {
            postId: this.postId,
            title: this.title,
            text: this.text
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

JSON.stringify 将自动调用它并用结果替换您的实例.

此外,您可能希望向类添加一个fromJSON方法,您可以使用该方法来恢复实例JSON.parse.在你的情况下这是微不足道的:

    static fromJSON(obj) {
        return new this(obj);
    }
Run Code Online (Sandbox Code Playgroud)

但是你可能需要在其他课程中更复杂的东西.