所有,我看到很多關於如何在SO中解析json到js對象(或將json轉換爲js對象)的示例。但是我沒有看到一個將json綁定到已經定義好的js對象的例子。現在,當我嘗試製作它時,我遇到了一些麻煩。請幫助我查看它。謝謝。JSON綁定到Javascript對象
我做了什麼至今看起來象下面這樣:
top=function()
{
this.encoding ='';
this.nodes=[];
this.lastid='';
//I don't how to defined the attributes key in json which is a object.
//I think there should exist a parse and toJson function;
//this.parse= function(jsonstring){...};
//this.toJson=function(){var jsonstr=....;return jsonstr;};
};
group=functon()
{
this.id='';
this.type='';
this.subnodes=[];
this.tagname='';
//....
}
top
是其中包含的block
不確定的數字是自包含對象的根。
和Json由Jackson生成,如下所示。
{
"nodes": [
{
"type": "group",
"id": 11,
"tagName": "blockrow",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "12"
//...more
},
"subNodes": [
{
"type": "group",
"id": 111,
"tagName": "blockcol",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "4"
},
"subNodes": [
{
"type": "group",
"id": 1111,
"tagName": "section",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"title": "NewSection",
"width": "12"
},
"subNodes": [
{
"type": "leaf",
"id": 11111,
"tagName": "message",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"key": "aa_login_success"
}
}
]
}
]
},
{
"type": "group",
"id": 112,
"tagName": "blockcol",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "4"
},
"subNodes": [
{
"type": "group",
"id": 1121,
"tagName": "section",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"title": "NewSection",
"width": "12"
},
"subNodes": [
{
"type": "leaf",
"id": 11211,
"tagName": "message",
"prefix": "aa",
"cutomTag": {
"type": "cutomTag",
"beginPos": 20,
"endPos": 50,
"id": -1
},
"attributes": {
"key": "aa_login_failed"
}
}
]
}
]
},
{
"type": "group",
"id": 113,
"tagName": "blockcol",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "4"
},
"subNodes": null
}
]
},
{
"type": "group",
"id": 12,
"tagName": "blockrow",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "12"
},
"subNodes": [
{
"type": "group",
"id": 121,
"tagName": "blockcol",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "6"
},
"subNodes": null
},
{
"type": "group",
"id": 122,
"tagName": "blockcol",
"prefix": "aa",
"cutomTag": null,
"attributes": {
"width": "6"
},
"subNodes": null
}
]
}
],
"version": 1,
"encoding": "unicode",
"lastId": 1
}
樣的代碼,我想象會看起來象下面這樣:
var curTop= new top();
curTop.parse(jsonstring);
//manipulate the curTop object...
//...
var jsonStr=curTop.toJson();
//convert object to json.
我希望我的方向迄今爲止要解決的問題是正確的,如果這是不對的,我希望你給我一些好評。
嗨,@Basarat,我可以這樣定義它嗎?'this.parse = function(jsonstring){...};'謝謝。 – 2013-03-22 05:52:39
這樣您將擁有每個實例的功能(對內存不好)。更何況你不能創建一個繼承鏈。 – basarat 2013-03-22 05:54:34
好的,我明白了。謝謝。 – 2013-03-22 05:56:30