Skip to main content
 首页 » 编程设计

json之Amber 和本地存储,asJSON

2024年05月06日30txw1958

我想使用 Amber ( on-line IDE ) 将 OrderedCollection 存储在 Web 浏览器的 localStorage 中,然后再检索它。

创建测试数据对象

| coll hcoll | 
 
coll := OrderedCollection new. 
coll add: 'abc'. 
coll add: 'xon'. 
 
hcoll := HashedCollection new. 
hcoll at: 'en' put: 'English'. 
hcoll at: 'fr' put: 'French'. 
hcoll at: 'ge' put: 'German'. 
 
coll add: hcoll. 

将测试数据对象存储在localStorage中

localStorage 是浏览器中的键值存储。这些值必须是字符串。

localStorage setItem: 'coll' value: coll asJSONString. 
 
 
"We set coll to nil to indicate that we  
are going to retrieve it back from the localStorage" 
 
coll := nil. 

取回存储的值

以下内容的 printIt

localStorage getItem: 'coll'  

给出

 '["abc","xon",{"en":"English","fr":"French","ge":"German"}]'  

这是一个 JSON 字符串。

如何取回 OrderedCollection coll

使用浏览器内置的 JSON 解析器

JSON parse: (localStorage getItem: 'coll') 

printIt 的结果是

an Array ('abc' 'xon' [object Object])  

(JSON parse: (localStorage getItem: 'coll')) class 

Array  

数组的第三个元素

((JSON parse: (localStorage getItem: 'coll')) at: 3) class 

是一个

JSObjectProxy 

问题

如何取回任意 JSON 对象(包含 JavaScript 数组和对象、OrderedCollections 和 HashedCollections、Smalltalk 中的字典)的 Smalltalk 表示形式?

注意

http://www.json.org

JSON 建立在两种结构之上:

  • 名称/值对的集合。在各种语言中,它被实现为对象、字典、哈希表或关联数组。
  • 值的有序列表。在许多语言中,这是以数组、列表或序列的形式实现的。

请您参考如下方法:

打印

  SmalltalkImage current readJSObject:  
            (JSON parse: (localStorage getItem: 'coll'))   

回馈

    an Array ('abc' 'xon' a Dictionary ('en' -> 'English' , 'fr' -> 'French' , 'ge' -> 'German'))  

评论

(JSON parse: (localStorage getItem: 'coll'))   

给出一个 JSProxyObject,然后通过方法 #readJSObject: 将其转换为 Amber 对象。此方法只是将调用重定向到底层 JavaScript 方法。