How can I Insert JSON object into Postgres using Java preparedStatement?
This behaviour is quite annoying since JSON strings are accepted without problems when used as literal strings in SQL commands.
There is a already an issue for this in the postgres driver Github repository (even if the problem seems the be the serverside processing).
Besides using a cast (see answer of @a_horse_with_no_name) in the sql string, the issue author offers two additional solutions:
- Use a parameter
stringtype=unspecified
in the JDBC connection URL/options.
This tells PostgreSQL that all text or varchar parameters are actually of unknown type, letting it infer their types more freely.
- Wrap the parameter in a
org.postgresql.util.PGobject
:
PGobject jsonObject = new PGobject(); jsonObject.setType("json"); jsonObject.setValue(yourJsonString); pstmt.setObject(11, jsonObject);
You can do it like this and you just need the json string:
Change the query to:
String query = "INSERT INTO table (json_field) VALUES (to_json(?::json))"
And set the parameter as a String.
pStmt.setString(1, json);
Passing the JSON as a String is the right approach, but as the error message tells you, you need to cast the parameter in the INSERT
statement to a JSON
value:
insert into the_table (.., evtjson, ..) values (.., cast(? as json), ..)
Then you can use pStmt.setString(11, dtlRec.toString())
to pass the value