In a Java 17 project I have this Redis client:
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class RedisClient {
private final HostAndPort hostAndPortConfig = new HostAndPort(REDIS_HOST, parseInt(REDIS_PORT));
private final JedisClientConfig clientConfig = DefaultJedisClientConfig.builder()
.clientName("test")
.password(REDIS_PASS)
.build();
private final PooledConnectionProvider provider = new PooledConnectionProvider(hostAndPortConfig, clientConfig);
private final UnifiedJedis unifiedJedis = new UnifiedJedis(provider);
private static RedisClient instance;
public static synchronized RedisClient getInstance() {
if (instance == null) {
instance = new RedisClient();
}
return instance;
}
public <T> void insertJson(String key, T object) {
unifiedJedis.jsonSet(key, object);
}
public void ping() {
unifiedJedis.ping();
}
}
When I try to setJson:
var user = new User().setDiscordName("testName");
redisClient.insertJson("test", user);
I'm getting this exception:
Exception in thread "main" redis.clients.jedis.exceptions.JedisDataException: expected value at line 1 column 1
at redis.clients.jedis.Protocol.processError(Protocol.java:96)
at redis.clients.jedis.Protocol.process(Protocol.java:137)
at redis.clients.jedis.Protocol.read(Protocol.java:192)
at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:335)
at redis.clients.jedis.Connection.getOne(Connection.java:317)
at redis.clients.jedis.Connection.executeCommand(Connection.java:131)
at redis.clients.jedis.executors.DefaultCommandExecutor.executeCommand(DefaultCommandExecutor.java:24)
at redis.clients.jedis.UnifiedJedis.executeCommand(UnifiedJedis.java:183)
at redis.clients.jedis.UnifiedJedis.jsonSet(UnifiedJedis.java:3841)
at redis.clients.jedis.json.RedisJsonCommands.jsonSet(RedisJsonCommands.java:9)
at dev.rifaii.database.RedisClient.insertJson(RedisClient.java:41)
at dev.rifaii.Main.main(Main.java:18)
I tried following the documentation on redis website: https://developer.redis.com/howtos/redisjson/using-java/ so I'm not sure what's going wrong
jsonSet(key, object)
expects an object whose toString()
would provide a valid JSON.
You can use jsonSetWithEscape(key, object)
to avoid the hassle.