Can Hibernate automatically map a HashMap to a string column? - json

I have a HashMap which was populated from form elements of an HTML page, and when I save it I need Hibernate to convert it automatically to a JSON string and also persist it as a JSON string. Is this doable in Hibernate? Or, can you tell Hibernate in the mapping file (or maybe, as an annotation) to call a Java method that converts HashMap to JSON, and persist the return value of that method, and vice-versa? (read JSON string and convert automatically to a HashMap).
Thanks for all the help!

Sure, you can just create a custom user type:
http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/types.html#types-custom
Hibernate will then use this to persist data to the database, and to read it back as object.

Related

Why an ArrayList Type of the object does not support the size() method which is a builtin method for the ArrayList Type Object?

The entire question is in java. I am trying to extract some information from a json data format, then I used an mapper object to
data = mapper.readValue(jsonData, new TypeReference<>(){});
to convert this into a List of HashMaps, in fact, printing data.get(0).getClass() gives me as an LinkedHashMap, when I run data.get(0).get("key") returns as an ArrayList, but when I do ```
data.get(0).get("key").size()
It complains, can anyone point out why and provide me any suggestion on how to get the associated values from the key?

Create list of custom objects from flat JSON data

I want to create an arraylist of type Adapter from a JSON. But since the JSON is not in arraylist format, I'm unable to use gson.fromJson() method.
Is there any way by which I can create a list of my custom object by parsing the following JSON?
JSON data:
"source":{"adapter-config.adapter[0].name":"testAdapter1",
"adapter-config.adapter[0].resolverName":"serviceResolver",
"adapter-config.adapter[0].parameters[0].key":"serviceId",
"adapter-config.adapter[0].parameters[0].value":"serviceIdPathInEvent",
"adapter-config.adapter[0].parameters[1].key":"appId",
"adapter-config.adapter[0].parameters[1].value":"appIdPathEvent",
"adapter-config.adapter[0].parameters[2].key":"env",
"adapter-config.adapter[0].parameters[2].value":"envPathInEvnet"}
My Adapter Object:
public class Adapter {
private String name;
private String resolverName;
private List<KeyValuePair<String, String>> attributeList;
}
Gson does not provide such functionality out of the box. However you can achieve this by manually reading the JSON data from a JsonReader, consuming the JSON property names with nextName() and then parsing them to determine which data they represent. You could either directly read from a JsonReader, or in case the shown JSON data is only an extract from a larger JSON document, you can implement a TypeAdapter for your List<Adapter>. That TypeAdapter could then either be registered with a GsonBuilder by providing new TypeToken<List<Adapter>>() {}.getType() as type, or you could annotate the field holding the List<Adapter> with #JsonAdapter.
For the actual parsing of List<Adapter>, I would recommend storing a current adapter (and its index in the list) in a local variable. Whenever you parse a JSON property name, you could then check if the index encoded in the name is equal to the index of the current adapter, then you are going to modify the existing instance, otherwise if the encoded index is equal to the index of the current adapter + 1 you create a new Adapter instance, add it to the list of adapters and reassign the current adapter variable and its index variable. Then you continue with parsing the remainder of the property name to find out which Adapter field values to set.
(In case you get stuck there, feel free to let me know in the comments and I can try to provide some concrete code; but it would probably be best if you tried it yourself first.)

How to represent an array of Strings in mySQLdatabase

I'm new using mySQL database. I have a class in Java that as an variable that is an array of strings.
I would like to save that array of strings on my database.
How can i represent my array of string in the mysql database?
thank you
I can think of some ways:
Serialize the object.
How does that work? First you need a table that can hold the class name and the object serialized. You need the class name for when you need to read the object from the database.
Sample code can be found here:
http://javapapers.com/core-java/serialize-de-serialize-java-object-from-database/,
and
http://www.java2s.com/Code/Java/Database-SQL-JDBC/HowtoserializedeserializeaJavaobjecttotheMySQLdatabase.htm
Sometimes all you need to serialize is not the object, but rather, the attributes of the object. In this case, you can use XML or JSON (for example).
In this case, create a String representation of your object and save it to the database as a text field.
You can map your object to one or more tables using any of the many ORM solutions, such as iBatis, Hibernate, etc.
http://java.dzone.com/articles/getting-started-ibatis-mybatis
http://hibernate.org/orm/
If what you need is to save some attributes of your object to the database then you can either use JDBC and just update the field, or use an ORM and create a POJO with only the attributes you'd like to save.

Grails, create domain object from json-string with has-many relation

I'm trying to parse a grails parameter map to a Json String, and then back to a parameter map. (For saving html form entries with constraint-violations)
Everything is fine as long as there is no hasMany relationship in the parameter-map.
I'm using
fc.parameter = params as JSON
to save the params as JSON String.
Later I'm trying to rebuild the parameter map and create a new Domain-Object with it:
new Foo(JSON.parse(fc.parameter))
Everything is fine using only 1:1 relationships (states).
[states:2, listSize:50, name:TestFilter]
But when I try to rebuild a params-map with multi-select values (states)
[states:[1,2], listSize:50, name:TestFilter]
I'm getting this IllegalStateException:
Failed to convert property value of type org.codehaus.groovy.grails.web.json.JSONArray to required type java.util.Set for property states; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [de.gotosec.approve.State] for property states[0]: no matching editors or conversion strategy found
I tried to use this, but without success:
JSON.use("deep") {
new Foo(JSON.parse(fc.parameter))
}
You can use JsonSlurper instead of the converters.JSON of grails, it maps JSON objects to Groovy Maps. I think this link also might help you.
Edit: Now, if the problem is binding the params map to your domain, you should try using bindData() method, like:
bindData(foo, params)
Note that this straightforward use is only if you're calling bindData inside a controller.
What seems to be happening in your case is that Grails is trying to bind a concrete type of List (ArrayList in the case of JsonSlurper and JSONArray in the case of converters.JSON) into a Set of properties (which is the default data structure for one-to-many associations). I would have to take a look at your code to confirm that. But, as you did substitute states: [1,2] for a method of your app, try another test to confirm this hypothesis. Change:
states:[1,2]
for
states:[1,2] as Set
If this is really the problem and not even bindData() works, take a look at this for a harder way to make it work using object marshalling and converters.JSON. I don't know if it's practical for you to use it in your project, but it sure works nicely ;)

Convert JSON formated String to JsonObject with Jayrock

I have a request parameter in my ASP.NET app. that is in JSON format, and I was wondering if there is a good (quick and easy) way to convert a JSON string to a Jayrocks JsonObject, so I can easily extract key-value pairs without the need to manually parse the string?
Assuming json is the variable containing JSON text, use Jayrock.Json.Conversion.JsonConvert.Import(json). What you will get back in return is either a JsonObject, JsonArray, JsonNumber, System.String, System.Boolean or a null reference depending on the root JSON value in the source JSON text. If you know it is going to be a JSON object for sure then you can safely cast the return value or use JsonConvert.Import<JsonObject>(json).
I would discourage working against JsonObject directly unless you particularly depend on one of its features. You should just pretend the JSON object you get back is a dictionary; either IDictionary or IDictionary<string, object>. With the latest version for .NET Framework 4, you can also work with a JsonObject as a dynamic object.
I don't know Jayrock, but if you want to accept a JSON object as a parameter of Action in MVC2 than the easiest way to do it is by using JsonValueProviderFactory from Futures assembly.
It's part of System.Web.Mvc in MVC3.