11

Mysql 5.7 introduced the JSON data type which offers tonnes of query functions.

Since there isn't a compatible resultset function, how and what to i do use retrieve the data stored in this datatype.

3
  • Have you tried reading it as String? Then you could use some library like Jackson to parse this string into a POJO. Commented Apr 7, 2017 at 17:20
  • no i haven't actually tried reading it. I couldn't find a matching function so i got confused. I have now saved it as LONGTEXT in mysql. that definitely converts to string Commented Apr 7, 2017 at 17:22
  • dev.mysql.com/doc/connector-j/5.1/en/… .... seems like it can't be done as of this moment Commented Apr 7, 2017 at 17:24

3 Answers 3

8

It should be rs.getString, because getString used with VARCHAR, TEXT, we can consider JSon like a String type, so you can get the result, using getString.


Simple Example

Double check with MySQL 5.7 and PostgreSQL 9.4 :

MySQL 5.7 SQL

create database db_test;
create table table_test(json JSON);
INSERT INTO table_test VALUES('{"key1": "value1", "key2": "value2"}');

CODE

public static void checkJSon() {
    try {
        Class.forName(DRIVER);
        Connection connection = DriverManager.getConnection(DB_URL, DB_username, DB_password);
        String q = "SELECT * FROM table_test";
        PreparedStatement preparedStatement = connection.prepareStatement(q);
        preparedStatement.execute();
        ResultSet rs = preparedStatement.executeQuery();
        while (rs.next()) {
            System.out.println(rs.getString("json"));
        }

    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
}

It print to me :

{"key1": "value1", "key2": "value2"}
Sign up to request clarification or add additional context in comments.

4 Comments

i am not saving JSON as a string inside varchar or text. I was talking about the new JSON data type dev.mysql.com/doc/connector-j/5.1/en/… according to mysql docs, the connector does not support this type yet
i know @Kushan for example you are using CREATE TABLE t1 (jdoc JSON); JSON in your database, so to get this result you have to use getString to get JSon
have you tested if this works? if so i'll accept your answer.
@Kushan yes double check with MySQL 5.7 and PostgreSQL 9.4 work perfectly
1

In case anyone is still looking, I was trying it with Mysql 5.7, but the methods suggested above don't handle non-ascii data quite well a lot of asian characters etc). They end up displaying as garbled.

The solution is to read the raw bytes using getBinaryStream. The code is demonstrated below:

public String fromJSON(ResultSet rs, String fieldName){
    InputStream is = rs.getBinaryStream(fieldName);
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String content = br.lines().reduce("", String::concat);
    br.close();
    return content;
}

The above could be encapsulated in a function fromJSON and used widely. e.g

PreparedStatement st = getStatement("select json from x;");
ResultSet rs = st.executeQuery();
while (rs.next()) {
    return fromJSON(rs, "json");
}

Comments

1

In case JDBC isn't a hard requirement, recent jOOQ versions implemented an out-of-the-box way to map SQL JSON values to arbitrary Java types using the popular JSON mapping libraries Jackson or gson (whichever can be found on your classpath). You can then write:

List<MyClass> list =
ctx.select(TABLE.ID, TABLE.JSON_COLUMN)
   .from(TABLE)
   .where(...)
   .fetchInto(MyClass.class);

With, for example:

public class MyClass {
    public int id;
    public MyOtherClass jsonColumn;
}

public class MyOtherClass {
    public String something;
    public List<String> list;
}

Assuming your JSON_COLUMN contains data of the form:

{
  "something": "x",
  "list": [ "a", "b", "c" ]
}

This also works with all the natively supported SQL/JSON functions, to create such JSON documents on the fly.

(Disclaimer: I work for the company behind jOOQ)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.