0

I am trying to create a deep copy of a JSON map in groovy for a build config script.

I have tried the selected answer

def deepcopy(orig) {
     bos = new ByteArrayOutputStream()
     oos = new ObjectOutputStream(bos)
     oos.writeObject(orig); oos.flush()
     bin = new ByteArrayInputStream(bos.toByteArray())
     ois = new ObjectInputStream(bin)
     return ois.readObject()
}

from this existing question but it fails for JSON maps with java.io.NotSerializableException: groovy.json.internal.LazyMap

how can I create a deep copy of the JSON map?

Community
  • 1
  • 1
kira_codes
  • 1,457
  • 13
  • 38
  • 2
    I think that, if you can, you should back up a bit further. The `JsonSlurper` in the Groovy API generates these `LazyMap` instances that play havoc with various aspects of enterprise development, most particularly bean serializability requirements (as you are discovering). If you can switch to `JsonServerClassic`, which generates regular Groovy/Java `LinkedHashMap` instances, then your "NotSerializable" problem should go away. – BalRog Feb 22 '17 at 19:46
  • 1
    @BalRog most probably a typo in JsonSlurperClassic class name – maoizm Jan 01 '22 at 11:16
  • Yes, and I realized it sometime in 2018, long after I was no longer allowed to edit my comment. D'oh! I should have put up a second comment, verbally correcting my typo, but I must have forgotten or gotten distracted. – BalRog Jan 18 '22 at 18:48

1 Answers1

1

Once you read the JSON, you have the copy.

import groovy.json.JsonSlurper
import groovy.json.JsonOutput

def json = new JsonSlurper().parseText('''{"l1": {"l2": {"l3": 42}}}''')
json.l1.l2.l3 = 23
assert '''{"l2":{"l3":23}}''' == JsonOutput.toJson(json.l1)
cfrick
  • 35,203
  • 6
  • 56
  • 68