总而言之,我看到了很多关于如何在 SO 中将 json 解析为 js 对象(或将 json 转换为 js 对象)的示例。但是我没有看到将 json 绑定到已定义的 js 对象的示例。现在我在尝试制作时遇到了一些麻烦。请帮我检查一下。谢谢。
到目前为止我所做的如下所示:
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.
我希望到目前为止我解决问题的方向是正确的,如果不正确,我希望你给我一些意见。