2011/8/8 Nick Ager <nick.ager(a)gmail.com>om>:
Hi,
I'm experimenting with a JSON converter for objects with Magritte
descriptions. So far I've added the following to GRObject:
jsonOn: aStream
| description |
description := self description.
description children isEmpty ifFalse: [
| first |
first := true.
aStream nextPut: ${.
description do: [ :each |
first
ifTrue: [ first := false ]
ifFalse: [ aStream nextPut: $, ].
aStream
json: each label;
nextPut: $:;
json: (each accessor read: self) ].
aStream nextPut: $} ]
you can then generate JSON from an object, for example:
((PRPage named: 'examplePage') contents: '!!Hello', String crlf,
'Hello
""world"" check') asJson
gives:
'{"Name":"examplePage","Visibility":false,"Navigation
Title":"ExamplePage","Tags":[],"Title":"ExamplePage","Owner":null,"Group":null,"Contents":{},"Plain
Text":"Hello\rHello world check","Environment":null,"Style
Sheet":null,"Shortcut Icon":null,"CSS Classes":null}'
The method fails with recursive structures, but otherwise is appears to work
well.
Recursive structures don't work in JSON in general.
Does this look like a sensible approach? Has anyone
else implemented
anything similar?
There is Magritte-Json in [1]. It gives you more control, you can
override the name of a property and choose not to serialize certain
objects. I found this necessary when implementing certain predefined
APIs. It's a bit more "magritty" in the sense that is uses reader and
writer objects. Though it could certainly be improved on. You can find
examples in [2].
[1]
http://source.lukas-renggli.ch/magritteaddons
[2]
http://www.squeaksource.com/orion
Cheers
Philippe