macromaniac
macromaniac

Reputation: 427

List of strings is not rendered to JSON

I have a domain class

class UserProfile {

    List<String> interests = [];
    ObjectId id;
    String username;
    String password;
    String email;

    static constraints = {

    }
}

which is properly persisted in mongodb by gorm

def user = new UserProfile(username:"name",password:"pass",email:"[email protected]",interests: ['women','dogfight']);
user.save()

which could be verified in mongo console:

{ "_id" : ObjectId("528fd78003646357efb421c0"), "email" : "[email protected]", "interests" : [ "women", "dogfight"], "password" : "pass", "username" : "name", "version" : 0 }

so i get this object by UserProfile.find() as JSON in controller and got

{"class":"domain.users.UserProfile","id":{"class":"org.bson.types.ObjectId","inc":-273407552,"machine":56910679,"new":false,"time":1385158528000,"timeSecond":1385158528},"email":"asd\u0040asd.com","password":"pass","username":"name"}

as you can see list of interests unfortunately was not rendered

I would appreciate any help. Thanx.

P.S. Grails v2.3.3

Upvotes: 0

Views: 194

Answers (3)

Naresha
Naresha

Reputation: 199

Specifying association in domain class should help.

static hasMany = [interests: String]

Upvotes: 1

Tom Metz
Tom Metz

Reputation: 919

Collection inside domain class is unnatural to GORM. When using SQL database, you'll be in trouble to persist such an entity. So I believe, the converters in Grails are ignoring these attributes.

Than you need to write your own marshaller, to make the conversion. There are many answers about Grails marshallers here at SO, or here is a nice blog post:

http://compiledammit.com/2012/08/16/custom-json-marshalling-in-grails-done-right/

Upvotes: 2

mlim1972
mlim1972

Reputation: 248

Try the following:

import grails.converters.JSON
…
JSON.use('deep')
render someObject as JSON

Reference can be found at http://grails.org/Converters+Reference

Upvotes: 0

Related Questions