PathOfNeo
PathOfNeo

Reputation: 1089

How to operate on json in grails session object

i want to store in session object a json object session.setAttribute("myjson",myjson)

where myjson has a structure like this:

{ 'name':'john', age: 23}
{ 'name':'doe', age: 44}
..etc

How can i do this and how can i retrieve this object lateron from session.getAttribute('myjson') and append a new value {} ?

Upvotes: 0

Views: 133

Answers (2)

dsharew
dsharew

Reputation: 10665

Just to give sample code:
You can use list of map as mentioned in the comment.

List<Map<String,Integer>> listInSesion = [] 
listInSession.add([ 'name':'john', age: 23])
listInSession.add([ 'name':'doe', age: 44])
.
.

session.setAttribute('listInSession',listInSession)

If you are getting the JSON from an HTTP request you can simply say:

listInSession = request.JSON

To get the list and add new ones:

listInSession = session.getAttribute('listInSession')
listInSession?.add([ 'name':'john', age: 23])
session.setAttribute('listInSession',listInSession)

Upvotes: 1

Joshua Moore
Joshua Moore

Reputation: 24776

There are many ways to accomplish this, but honestly, you need to ask yourself "Is this really the right thing to do?". Why? Because storing anything in the session should be a last resort and should be kept to a bare minimum when you have to. Using the session in any HTTP environment kills performance and makes your application much more difficult to scale horizontally.

Keeping that in mind, you can always use org.codehaus.groovy.grails.web.json.JSONObjects and the grails.converters.JSON converter to accomplish this. Though, using a List of Maps might be easier.

Upvotes: 2

Related Questions