1

I have a JSON object that I insert into my MySQL DB.

ps = con.prepareStatement("INSERT INTO tableA(a, b, c, d_json)" +
                    " VALUES(?,?,?,cast(? AS JSON))", Statement.RETURN_GENERATED_KEYS);
// some code
ps.setObject(4, jsonValue);

I insert a hashmap of string as :

    Map<String, String> map = new HashMap<String, String>();
    map.put("key", "value");
    map.put("key1", "value1");
    map.put("key2", "value2");

However the json get encoded as following :

'"base64:type15:rO0ABXNyABFqYXZhLnV0aWwuSGFzaE1hcAUH2sHDFmDRAwACRgAKRvckkACXRocmVz\naG9sZHhwP0AAAAAAAAx3CAAAABAAABnZhbHVlMXQABGtleTJ0AAZ2YWx1ZTJ0\nAANrZXl0AAV2YWx1ZXg="'

I would like to insert a string instead of this. I saw some posts on S.O but I did not find any proper way to fix it. Any help would be appreciated. Thanks !

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Sox -
  • 592
  • 1
  • 9
  • 28

2 Answers2

1

The Java Mysql Driver does not support automatic conversion of Hashmaps. In fact if you use an unkown type in setObject, it will use default Java Serialization to convert it to something it can handle. The database receives a byte array containing the serialized HashMap. The cast(? as JSON) converts that into something that can be stored in the column, which is the BASE64 encoded byte array.

You need to convert your HashMap to a JSON String in your Java code before sending it to the database.

Markus Heberling
  • 835
  • 13
  • 18
  • 1
    Thanks a lot for answering and explaining why it did not work. I accepted Piotr 's answer but yours is as good as his ! – Sox - Mar 04 '20 at 09:22
1

You can't directly write Java object into MySQL - you need to convert your map to JSON string before writing it to table column. According to official docs: "Attempting to insert a value into a JSON column succeeds if the value is a valid JSON value, but fails if it is not".

Here is an example (Jackson):

import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {

  private static final ObjectMapper objectMapper = new ObjectMapper();

  public static String toJSON(Map<String, String> map) throws JsonProcessingException {
    return objectMapper.writeValueAsString(map);
  }
}

Another option would be to create one additional column, e, and then simply write map to two columns: map(k,v) => d(k), e(v)

Piotr Niewinski
  • 1,298
  • 2
  • 15
  • 27