
当使用jedis客户端的`jsonget`方法从redis获取json数据时,如果其中包含字节数组(如xml字符串的字节表示),可能会因底层json库(如gson或org.json)的默认行为,导致数字被统一上转型为`double`类型,从而在输出中显示`.0`后缀。本文将深入探讨此问题产生的原因,并提供三种有效的解决方案:数据后处理、通过指定类型和路径进行精确获取,以及执行原始redis命令以完全控制数据解析。
在使用UnifiedJedis的jsonGet方法获取存储在Redis中的JSON数据时,开发者可能会遇到一个常见的问题:原本期望获取的是字节数组(例如,一个XML字符串的ASCII值序列),但实际返回的数值却带有.0后缀,表现为double类型(例如,[60.0, 63.0, 120.0, ...])。
这个问题通常源于Jedis内部使用的JSON处理库,如Gson或org.json:json。这些库在默认情况下,会将JSON中的所有数字类型统一上转型为Java的double类型,以确保兼容性和精度,尤其是在无法确定原始数字具体类型时。因此,即使Redis中存储的是表示字节的整数值,经过这些库解析后,也会被转换为double类型。
例如,以下Java代码片段展示了该问题:
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.UnifiedJedis;
public class JedisJsonGetIssue {
public static void main(String[] args) {
HostAndPort config = new HostAndPort("localhost", 6379);
UnifiedJedis client = new UnifiedJedis(config);
String key = "StandaloneResponse:9b970b5f-32c2-4265-92cb-9af9d6707782";
// 假设Redis中存储的JSON数据在.variables.ReturnValue路径下包含一个字节数组
// 例如:{"variables": {"ReturnValue": [60, 63, 120, ...]}}
Object object = client.jsonGet(key);
System.out.println(object);
// 预期输出可能包含:ReturnValue=[60.0, 63.0, 120.0, ...]
client.close();
}
}为了解决这个问题,并获取原始的字节数组表示,我们可以采用以下几种策略。
一种直接的方法是在获取到Object类型的结果后,对其进行遍历和类型转换。由于jsonGet通常返回一个Map或List的嵌套结构,我们可以将其强制转换为LinkedHashMap,然后定位到包含double值的字段,并将其转换回byte类型。
实现思路:
示例代码(概念性):
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.UnifiedJedis;
import java.util.List;
import java.util.LinkedHashMap;
import java.util.ArrayList;
public class JedisJsonPostProcess {
public static void main(String[] args) {
HostAndPort config = new HostAndPort("localhost", 6379);
UnifiedJedis client = new UnifiedJedis(config);
String key = "StandaloneResponse:9b970b5f-32c2-4265-92cb-9af9d6707782";
try {
Object result = client.jsonGet(key);
if (result instanceof LinkedHashMap) {
LinkedHashMap<String, Object> rootMap = (LinkedHashMap<String, Object>) result;
if (rootMap.containsKey("variables") && rootMap.get("variables") instanceof LinkedHashMap) {
LinkedHashMap<String, Object> variablesMap = (LinkedHashMap<String, Object>) rootMap.get("variables");
if (variablesMap.containsKey("ReturnValue") && variablesMap.get("ReturnValue") instanceof List) {
List<?> rawReturnValue = (List<?>) variablesMap.get("ReturnValue");
List<Byte> byteReturnValue = new ArrayList<>();
for (Object val : rawReturnValue) {
if (val instanceof Double) {
byteReturnValue.add(((Double) val).byteValue());
} else {
// 处理非Double类型,例如抛出异常或记录警告
System.err.println("Warning: Unexpected type in ReturnValue list: " + val.getClass().getName());
}
}
variablesMap.put("ReturnValue", byteReturnValue); // 更新为正确的字节列表
System.out.println("Processed ReturnValue: " + byteReturnValue);
}
}
System.out.println("Full processed object: " + rootMap);
} else {
System.out.println("Unexpected result type: " + result.getClass().getName());
}
} finally {
client.close();
}
}
}注意事项:
Jedis提供了更强大的jsonGet重载方法,允许你指定期望的返回类型和JSON路径。这是解决此类问题的推荐方法,因为它直接在Jedis层面处理类型转换,避免了手动后处理。
实现思路:
示例代码:
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path;
public class JedisJsonGetWithType {
public static void main(String[] args) {
HostAndPort config = new HostAndPort("localhost", 6379);
UnifiedJedis client = new UnifiedJedis(config);
String key = "StandaloneResponse:9b970b5f-32c2-4265-92cb-9af9d6707782";
try {
// 直接获取.variables.ReturnValue路径下的字节数组
Byte[] returnValue = client.jsonGet(key, Byte[].class, Path.of(".variables.ReturnValue"));
if (returnValue != null) {
System.out.print("Retrieved ReturnValue as Byte array: [");
for (int i = 0; i < returnValue.length; i++) {
System.out.print(returnValue[i]);
if (i < returnValue.length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
// 示例:将字节数组转换回字符串
byte[] primitiveBytes = new byte[returnValue.length];
for (int i = 0; i < returnValue.length; i++) {
primitiveBytes[i] = returnValue[i];
}
System.out.println("Decoded String: " + new String(primitiveBytes));
} else {
System.out.println("ReturnValue not found or could not be cast to Byte[].");
}
} finally {
client.close();
}
}
}注意事项:
对于需要极致控制或处理Jedis默认JSON解析行为无法满足的场景,可以直接执行原始的Redis命令。这种方法完全绕过了Jedis的内置JSON解析器,允许开发者自行处理Redis返回的原始数据。
实现思路:
示例代码:
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.args.CommandArguments;
import redis.clients.jedis.json.JsonProtocol;
import com.google.gson.Gson; // 假设使用Gson进行手动解析
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import java.util.LinkedHashMap;
public class JedisRawCommand {
public static void main(String[] args) {
HostAndPort config = new HostAndPort("localhost", 6379);
UnifiedJedis client = new UnifiedJedis(config);
String key = "StandaloneResponse:9b970b5f-32c2-4265-92cb-9af9d6707782";
try {
// 执行原始JSON.GET命令
Object rawResult = client.executeCommand(new CommandArguments(JsonProtocol.JsonCommand.GET).add(key));
if (rawResult instanceof String) {
String jsonString = (String) rawResult;
System.out.println("Raw JSON String from Redis: " + jsonString);
// 手动解析JSON字符串
Gson gson = new Gson();
// 假设我们知道顶层是一个LinkedHashMap
Type type = new TypeToken<LinkedHashMap<String, Object>>() {}.getType();
LinkedHashMap<String, Object> parsedMap = gson.fromJson(jsonString, type);
// 继续手动解析到ReturnValue
if (parsedMap != null && parsedMap.containsKey("variables")) {
LinkedHashMap<String, Object> variables = (LinkedHashMap<String, Object>) parsedMap.get("variables");
if (variables != null && variables.containsKey("ReturnValue")) {
// 在Gson解析时,如果JSON中的数字是整数,Gson默认会解析为Double
// 所以这里仍然需要从List<Double>转换为List<Byte>
List<Double> rawBytesAsDoubles = (List<Double>) variables.get("ReturnValue");
if (rawBytesAsDoubles != null) {
List<Byte> actualBytes = new ArrayList<>();
for (Double d : rawBytesAsDoubles) {
actualBytes.add(d.byteValue());
}
System.out.println("Manually parsed ReturnValue as Byte array: " + actualBytes);
}
}
}
} else {
System.out.println("Unexpected raw result type: " + rawResult.getClass().getName());
}
} finally {
client.close();
}
}
}注意事项:
Jedis jsonGet方法返回double类型而非原始字节值的问题,主要是由于其底层JSON解析库的默认行为。为了解决这个问题,我们提供了三种策略:
在大多数情况下,使用client.jsonGet(key, Byte[].class, Path.of(".variables.ReturnValue"))这种指定类型和路径的方法是最佳实践,因为它兼顾了代码的简洁性、效率和准确性。只有在特定需求下,例如需要处理非常规的JSON数据或对解析过程有极高定制要求时,才考虑采用后两种更复杂的方法。
以上就是Jedis jsonGet 方法返回字节数组值末尾出现 .0 的处理策略的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号