我希望能夠將字符串解析爲可以使用點符號訪問的對象,例如, myobject.property,而不是數組符號,例如MYOBJECT [ '屬性']。數組表示法正常工作。這是迄今爲止我所擁有的。使用Dart解析JSON
我有一些XML:
<level1 name="level1name">
<level2 type="level2Type">
<entry>level2entry</entry>
<entry>level2entry</entry>
</level2>
</level1>
哪個轉換爲JSON:
{
"level1": {
"name": "level1name",
"level2": {
"type": "level2Type",
"entry": [
"level2entry",
"level2entry"
]
}
}
}
我有以下達特代碼:
Object jsonObject = JSON.parse("""{
"level1": {
"name": "level1name",
"level2": {
"type": "level2Type",
"entry": [
"level2entry",
"level2entry"
]
}
}
}
""");
print("my test 1 == ${jsonObject}");
print("my test 2 == ${jsonObject['level1']}");
print("my test 3 == ${jsonObject['level1']['name']}");
其產生的(期望的)輸出:
my test 1 == {level1: {name: level1name, level2: {type: level2Type, entry: [level2entry, level2entry]}}}
my test 2 == {name: level1name, level2: {type: level2Type, entry: [level2entry, level2entry]}}
my test 3 == level1name
但是當我嘗試:
print("my test 1 == ${jsonObject.level1}");
我得到如下:
Exception: NoSuchMethodException : method not found: 'get:level1'
Receiver: {level1: {name: level1name, level2: {type: level2Type, entry: [level2entry, level2entry]}}}
Arguments: []
Stack Trace: 0. Function: 'Object.noSuchMethod' url: 'bootstrap' line:717 col:3
理想情況下,我想一個對象,我可以訪問使用點符號,沒有編譯器給予警告有關對象沒有財產。我試過如下:
class MyJSONObject extends Object{
Level1 _level1;
Level1 get level1() => _level1;
set level1(Level1 s) => _level1 = s;
}
class Level1 {
String _name;
String get name() => _name;
set name(String s) => _name = s;
}
...
MyJSONObject jsonObject = JSON.parse("""{
"level1": {
"name": "level1name",
"level2": {
"type": "level2Type",
"entry": [
"level2entry",
"level2entry"
]
}
}
}
""");
...
print("my test 1 == ${jsonObject.level1.name}");
而是給予我「level1name」的希望,我得到:
Exception: type 'LinkedHashMapImplementation<String, Dynamic>' is not a subtype of type 'MyJSONObject' of 'jsonObject'.
什麼我錯在這裏做什麼?有什麼辦法可以做我想要的嗎?謝謝。
這是一種旁白;你應該能夠從一個對象轉換爲JavaScript,並從JavaScript轉換爲JSON。 – will 2014-04-29 22:51:10