Deserializing JavaScript object instance

前端 未结 5 1219
悲哀的现实
悲哀的现实 2021-01-23 11:56

I am working on an app that heavily uses JavaScript. I am attempting to include some object-oriented practices. In this attempt, I have created a basic class like such:

相关标签:
5条回答
  • 2021-01-23 12:15

    I know this question is answered already, however I stumbled upon this by accident and wanted to share a solution to this problem, if anyone is interested.

    instead of doing this:

    var item = window.localStorage.getItem("itemKey");
    item = JSON.parse(item);
    item.save();
    

    do something like this:

    // get serialized JSON
    var itemData = window.localStorage.getItem("itemKey");
    //instantiate new Item object
    var item = new Item();
    // extend item with data
    $.extend(item, JSON.parse(itemData));
    
    // this should now work
    item.save();
    

    this will work so long as the function you are wanting to call (ie, save()) is prototypal and not an instance method (often times the case, and is indeed the case in the OP's original question.

    the $.extend method is a utility method of jquery, but it is trivial to roll your own.

    0 讨论(0)
  • 2021-01-23 12:22

    Disclaimer

    Not a full time time J.S. Developer, answer may have some minor bugs:

    Long Boring Explanation

    As mentioned by @JAAulde, your object cannot be serialized into JSON, because has functions, the technique that you are using doesn't allow it.

    Many people forget or ignore that the objects that are used in an application, may not be exactly the same as saved / restored from storage.

    Short & quick Answer

    Since you already encapsulate the data members of your object into a single field, you may want to try something like this:

    // create J.S. object from prototype
    Item item = new Item();
    
    // assign values as you app. logic requires
    item.data.name = "John Doe";
    item.data.description = "Cool developer, office ladies, love him";
    
    // encoded item into a JSON style string, not stored yet
    var encodedItem = JSON.stringify(item.data)
    
    // store string as a JSON string
    window.localStorage.setItem("itemKey", encodedItem);
    
    // do several stuff
    
    // recover item from storage as JSON encoded string
    var encodedItem = window.localStorage.getItem("itemKey");
    
    // transform into J.S. object
    item.data = JSON.parse(encodedItem);
    
    // do other stuff
    

    Cheers.

    0 讨论(0)
  • 2021-01-23 12:24

    You cant do that, how can javascript possibly knows that item have a save function ? json doesnt allow functions as datas. just read the json spec , you cant save functions.

    what you need to do is to create a serialize and deserialize method in the hash you want to stock. that will specifiy what to export and how you can "wake up" an object after parsing the corresponding json string.

    0 讨论(0)
  • 2021-01-23 12:37

    Short answer:

    Functions cannot be serialized into JSON.

    Explanation:

    JSON is a cross-platform serialization scheme based on a subset of JS literal syntax. This being the case, it can only store certain things. Per http://www.json.org/ :

    • Objects: An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
    • Arrays: An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
    • values: A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

    Functions cannot be serialized into JSON because another non-JS platform would not be able to unserialize and use it. Consider the example in reverse. Say I had a PHP object at my server which contained properties and methods. If I serialized that object with PHP's json_encode() and methods were included in the output, how would my JavaScript ever be able to parse and understand PHP code in the methods, let alone use those methods?

    What you are seeing in your resulting JSON is the toString() value of the function on the platform you're using. The JSON serilizer calls toString() on anything being serialized which isn't proper for JSON.

    I believe your solution is to stop storing instances in JSON/local storage. Rather, save pertinent data for an instance which you set back to a new instance when you need.

    0 讨论(0)
  • 2021-01-23 12:37

    You can only store plain Objects in DOMstorages (cookies, urlparams..., everything that needs [de]serialisation through JSON.stringify/JSON.parse). So what you did when sending the ajax data

    ajaxsend(this.data);
    

    also applies to string serialisation. You can only store the data, not the instance attributes (like prototype, constructor etc.). So use

    savestring(JSON.stringify(item.data));
    

    which is possible because item.data is such a plain Object. And when restoring it, you will only get that plain data Object back. In your case it's easy to reconstruct a Item instance from plain data, because your Items hold their values (only) in a public available property:

    var item = new Item;
    item.data = JSON.parse(getjsonstring());
    
    0 讨论(0)
提交回复
热议问题