How to generate a json string for an object and then restore it
Jing, mqjing@gmail.com
GitHub: Download
Google Doc: This document
如何把物件的資料存到資料庫或檔案, 我記得這功能叫做 serialization. 既然 Javascript 有 class, 那麼我要怎麼做才能把物件變成 JSON 字串? 如何 restore 回來?
下面的範例教你.
Object -> JSON string
objMessage = new ...
let strJSON = JSON.stringify(objMessage)
JSON -> Object
let restoreObj2 = JSON.parse(strJson);
Example
class BrokerClass{
constructor(strIP, intPort) {
this._strIP = strIP;
this._intPort = intPort;
}
}
class MessageClass{
constructor(objPayload) {
this._messageiD = 1;
this._data = objPayload; // _data 是 BrokerClass 型態的物件
this._expiredtime = 2
}
print(){
console.log("print");
}
}
function main() {
// Create Objects
let objBroker = new BrokerClass('192.168.1.10', 1234);
var objMessage = new MessageClass(objBroker);
// Object -> JSON string
let strJson = JSON.stringify(objMessage);
console.log('JSON String = ' + strJson); // get the json string
// JSON -> Object
let restoreObj2 = JSON.parse(strJson);
//Verification
console.log('restoreObj2._messageiD = ' + restoreObj2._messageiD);
console.log('restoreObj2._data = ' + restoreObj2._data._strIP);
restoreObj2.__proto__ = MessageClass.prototype; // 不做這個, 下面呼叫 print 會失敗!
restoreObj2.print();
}
main();
|
比較差的方法
GitHub: Download
Object to JSON
return JSON.stringify({"_strName":this._strName, "_intAge":this._intAge});
JSON to Object
用轉型的方式
var obj = JSON.parse(strJSONString);
obj.__proto__ = MyClass.prototype
Example
class MyClass{
constructor(strName, intAge) {
this._strName = strName;
this._intAge = intAge;
}
toJson(){
return JSON.stringify({"_strName":this._strName, "_intAge":this._intAge});
}
print(){
console.log("print");
}
}
function main() {
// Create objects
let obj = new MyClass("Jing", "1234");
console.log("Json" + obj.toJson());
let obj2 = new MyClass("Tom", "57");
console.log("Json" + obj2.toJson());
// Restore object
let restoreObj2 = JSON.parse(obj.toJson());
restoreObj2.__proto__ = MyClass.prototype;
console.log('restoreObj2 = ', restoreObj2);
console.log('restoreObj2._strName = ' + restoreObj2._strName);
}
|