I am new to groovy Grails and trying to understand how to work with GORM
We have SQL table with column of string type that holds JSON String representing some object
(I can't alternate db design)
I understand that in groovy Model objects represent SQL records and in general we can use marshallers to render objects to JSON
But what I need is to get, create or save Model object that have Json string column that will be rendered to an object in groovy, but can't find any information on how to do it
for example to simplify i will have following table : id(number), json(longstring)
and in JSON:
{"name":"object1", "list":[{"item":"item1", "type":"type1"},{"item":""item2", "type":"type2"},..]}
and following classes:
class MainModelClass {
Long id
MyObject o
...
}
class MyObject {
List<Item> items
...
}
class Item {
String item
String type
...
}
How can I make the Model object parse the JSON to Object structure
Thanks
You could use a simple trick with a transient property like so:
import groovy.json.*
class MainModelClass {
String originalJson
static final JsonSlurper slurper = new JsonSlurper()
MyObject getMyObject(){
slurper.parseText( originalJson ) as MyObject
}
void setMyObject( MyObject myObject ){
originalJson = JsonOutput.toJson myObject
}
static transients = [ 'myObject' ]
}
You might want to use Jackson Mapper to have finer control over marshalling.
Related
I would like to make a Kotlin class serializable using Kotlin serialization.
The class is very simple, something like this:
#Serializable(with = CustomSerializer::class)
data class MyObject(val keys: Set<String>)
Now, I need the serialization format to be a JSON object where the keys are given by the Set<String> and the values are always empty JSON objects.
Example:
val example = MyObject(setOf("abc", "def"))
Should serialize to:
{ "abc": {}, "def": {} }
The reason is that this object is being sent to an API where that's how they want the JSON to look like... the empty objects could contain some directives but I don't want or need to use those.
Having trouble doing that by just reading the documentation.
I've found one way to do it... and it seems simple enough!
I realized that I can get a serializer of empty Objects almost for free with this:
#Serializable
private object EmptyMap
Now, I can write a custom serializer in a straightforward way:
object MyObjectSerializer : KSerializer<MyObject> {
private val _delegate = MapSerializer(String.serializer(), EmptyMap.serializer())
override val descriptor: SerialDescriptor = _delegate.descriptor
override fun serialize(encoder: Encoder, value: MyObject) {
val data = value.keys.associateWith { EmptyMap }
encoder.encodeSerializableValue(_delegate, data)
}
override fun deserialize(decoder: Decoder): MyObject {
val value = decoder.decodeSerializableValue(_delegate)
return MyObject(value.keys)
}
}
Now all that's left to do is to apply the serializer on the type, which can be done with:
#Serializer(with = MyObjectSerializer)
data class MyObject(val keys: Set<String>)
Running Json.encodeToString(example) on the examples works perfectly.
Okay first off , I am extremely new to grails. And I am quite stuck at converting a domain object to JSON.
My domain class looks as follows
class MoneyTransfer {
Account fromAccount
Date sourceTransactionDate
TransactionStatus sourceTransactionStatus
String sourceTransactionMessage
Account toAccount
Date destinationTransactionDate
TransactionStatus destinationTransactionStatus
String destinationTransactionMessage
double amount
String note
Status status
PianoUser creator
String errorMessage
// predefined grails date create & modified & version
Date dateCreated
Date lastUpdated
String uniqueId
}
How does one convert such a domain class's object to JSON object ?
I tried using grails.converters.JSON and grails.converters.deep.JSON as follows
class MyTransferController{
def xyz(){
MoneyTransfer monetTransferInstance = getMoneyTransferInstance();
def moneyTransferJson = fundTrasnferInstance as JSON //doesnot work
}
}
How do I convert my domain class's object to JSON Object? Any suggestion would be appreciated.
Try this
import grails.converters.JSON
class MyTransferController {
def xyz() {
MoneyTransfer moneyTransferInstance = getMoneyTransferInstance()
render moneyTransferInstance as JSON
}
}
I am using jackson json api to map json data to java objects. All is well in case of same object attribute names with json attributes. Now i have a situation where i am getting json data attribute with -. (my-name).
In java we can't include - in variable names.
import org.codehaus.jackson.map.ObjectMapper;
private static final ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue("{my-name:\"abcd\"}", User.class);
public class User {private String my_name; /*get-set methods*/}
Is there anything i need to apply in User.class.
I don't want to change my code so much.
In your java class you can give any name as you like
Ex. private String myName;
But in the setter method just write:
#JsonProperty("my-name")
public void setMyName(String myName) {
this.myName = myName;
}
I am getting following JSON string through http webservice:
Raw JSON String:
[
{
field1OfClass1:"someValue",
field2OfClass1:"someValue",
field1OfClass2:"someValue",
field2OfClass3:"someValue"
}
]
Classes:
class Class1
{
String field1;
String field2;
}
class Class2
{
String field1;
}
class Class3
{
String field2;
}
In GSON is there any way to parse above said JSON string with the fields of depicted classes?
Thanks
As best I know, there is no built-in feature of Gson to automagically map the example JSON structure to the example Java data structure in the original question. Custom deserialization processing is necessary.
So I have a class that I was planning on using for simple JSON serialization.
public class Thing {
private int field1;
private String some_other_field;
private List<SubType> subs;
private list<AnotherType> another;
public String toJson() {
Gson g = new Gson();
g.toJson(this);
}
}
So the documentation shows that if you want to serialize generic types, you need to specify a TypeToken:
Type listtype = new TypeToken<List<SubType>>() {}.getType();
gson.toJson(subs, listtype);
But then, how does this work if I have a whole class I want to serialize for? Where do I get to specify the serialization type for those two List<> types so that I can just pass the whole object in and get a serialized output? Is that even possible?
From the doc it seems that if you serialize a complete object with toJson(...), it deals with the generics attributes properly.
toJson(Object)
"Note that this method works fine if the any of the object fields are of generic type, just the object itself should not be of a generic type"
What output did you get with your object ?