pharo

Read nested Json Mapping with NeoJSON


I have a Json that has this format:

{
  "id": 12,
  "fields": {
    "name": "Hello Pharo"
  }
}

And I would like to import it in a Pharo Object. My Pharo class has two attributes: id, and name. To perform the deserialisation I'm using NeoJSON. I got it for id, but how to map an inner attribute such as name

| reader |
reader := NeoJSONReader on: entity contents readStream.
reader
  for: MyObject
  do: [ :mapping | mapping mapInstVars: #( id ) ].
reader nextAs: MyObject] 

Do you know how one can use the NeoJSON lib to perform such read mapping?


Solution

  • Not my own answer, but I got this asking around:

    json := '{
      "id": 12,
      "fields": {
        "name": "Hello Pharo"
      }
    }'.
    
    "Use Association as a domain object, key=id, value=fields.name"
    
    reader := NeoJSONReader on: json readStream.
    reader for: Association do: [ :mapping |
        mapping mapInstVar: #key to: #id.
        mapping mapProperty: #fields 
            getter: [ :association | { #name -> association value } asDictionary ]
            setter: [ :association :value | association value: (value at: #name) ] ].
    reader nextAs: Association. 
    
        12->'Hello Pharo'.
    
    String streamContents: [ :out |
        (NeoJSONWriter on: out)
            for: Association do: [ :mapping |
                mapping mapInstVar: #key to: #id.
                mapping mapProperty: #fields 
                    getter: [ :association | { #name -> association value } asDictionary ]
                    setter: [ :association :value | association value: (value at: #name) ] ];
            nextPut: 12 -> 'Hello Pharo' ].
    
        '{"id":12,"fields":{"name":"Hello Pharo"}}'.