Reputation: 3128
I have such controller in my grails project:
def submit() {
def json = request.JSON
Share share = new Share(json)
share.save(flush: true, failOnError: true)
}
Class Share looks like this:
class Share {
String timestamp
String deviceName
String originMessage
Share(JSONObject originalMessage) {
println "Run JSON constructor"
println "$originalMessage"
originMessage = originalMessage.toString()
timestamp = originalMessage.timestamp
deviceName = originalMessage.device
}
It recives JSON request and try to persist in data base.
I get such error in my console on failOnError:
A lot of dancing around find one possible way: in controller convert JSON to string and pass it in constructor where parameter would be type String and then parse it back in JSON using JSON converter. But why I can not pass JSON Object as parameter correctly. What happens?
Upvotes: 1
Views: 921
Reputation: 187399
I don't see much point in declaring this constructor because domain classes already have an implicit constructor that takes a Map
argument. You could call this constructor with the JSONObject
because this class implements Map
, e.g.
class Share {
String timestamp
String deviceName
String originMessage
}
def json = request.JSON
Share share = new Share(json)
The reason for these errors
Field error in object 'com.entity.Share' on field 'deviceName': rejected value [null];
Field error in object 'com.entity.Share' on field 'originMessage': rejected value [null]; codes
is that your JSONObject
instance does not have non-null properties named deviceName
or originMessage
.
Either you need to figure out why these properties are missing, or allow these properties to be null by adding the following constraints to the domain class
class Share {
String timestamp
String deviceName
String originMessage
static constraints = {
deviceName nullable: true
originMessage nullable: true
}
}
Upvotes: 2