Actually, for the reading part, this variation might be clearer: (NeoJSONReader on: '{"id":13,"data":"aaa","extent":{"x":250,"y":110}}' readStream) for: NeoJSONTestObject2 customDo: [ :mapping | mapping reader: [ :jsonReader | | object | object := NeoJSONTestObject2 new. jsonReader parseMapKeysDo: [ :key | key = #id ifTrue: [ object id: jsonReader parseValue ]. key = #data ifTrue: [ object data: jsonReader parseValue ]. key = #extent ifTrue: [ jsonReader parseMapKeysAndValuesDo: [ :key2 :value | key2 = #x ifTrue: [ object width: value ]. key2 = #y ifTrue: [ object height: value ] ] ] ]. object ] ]; nextAs: NeoJSONTestObject2
On 27 Sep 2013, at 18:21, Sven Van Caekenberghe <s...@stfx.eu> wrote: > Norbert, > > On 25 Sep 2013, at 18:21, Norbert Hartl <norb...@hartl.name> wrote: > >> Is it possible to make a mapping for NeoJSON that an object shape maps to a >> different shape. I mean if it is possible to have a class with instVars: >> >> Foo >> +name >> +x >> +y >> >> that maps to >> >> { >> 'name' ; …, >> 'point' : { >> x : …, >> y : …. } >> } >> >> thanks, >> >> Norbert > > With custom mappings you can do pretty much what you want. > > Here is one way it can be done: > > String streamContents: [ :out | > (NeoJSONWriter on: out) > mapAllInstVarsFor: Point; > for: NeoJSONTestObject2 customDo: [ :mapping | > mapping writer: [ :jsonWriter :object | > jsonWriter writeMapStreamingDo: [ :jsonMapWriter | > jsonMapWriter > writeKey: #id value: object id; > writeKey: #data value: object data; > writeKey: #extent value: object width @ object height ] ] ]; > nextPut: NeoJSONTestObject2 example1 ]. > > (NeoJSONReader on: '{"id":13,"data":"aaa","extent":{"x":250,"y":110}}' > readStream) > for: NeoJSONTestObject2 customDo: [ :mapping | > mapping reader: [ :jsonReader | | object | > object := NeoJSONTestObject2 new. > jsonReader parseMapKeysAndValuesDo: [ :key :value | > key = #id ifTrue: [ object id: value ]. > key = #data ifTrue: [ object data: value ]. > key = #extent ifTrue: [ object width: (value at: #x); height: (value > at: #y) ] ]. > object ] ]; > nextAs: NeoJSONTestObject2. > > Regards, > > Sven