You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jedis读取JSON中指定键对应的值?

Fixing Your Jedis + JSON Retrieval Code

Hey there! Let's sort out your Jedis code issue quickly. The key thing you're missing here is that jedis.get() returns a plain String, not a ready-to-use JSONObject—so your current code will throw a compilation error right where you try to assign the result of jedis.get(productID) to a JSONObject variable.

Here's what's going wrong in your original code:

Jedis jedis = pool.getResource(); jedis.select(1); String attributeName = jedis.get(facet); jedis.select(0); JSONObject productJson = jedis.get(productID); String attributeValue = productJson.getString(attributeName);
  • jedis.get(productID) returns a String (the JSON data stored in Redis), but you're trying to assign it directly to a JSONObject reference—this won't work.
  • Also, it's good practice to handle resource cleanup for Jedis (to avoid connection leaks) and add error handling for invalid JSON.

Corrected Code Example

Let's use Alibaba's FastJSON (a common JSON library for Java) to parse the string into a JSONObject. First, make sure you have the FastJSON dependency in your project. Then:

// Use try-with-resources to auto-close the Jedis connection
try (Jedis jedis = pool.getResource()) {
    // Get attribute name from DB 1
    jedis.select(1);
    String attributeName = jedis.get(facet);
    
    // Get product JSON string from DB 0
    jedis.select(0);
    String productJsonString = jedis.get(productID);
    
    // Check if the JSON string exists before parsing
    if (productJsonString == null) {
        throw new IllegalArgumentException("No product found with ID: " + productID);
    }
    
    // Parse the string into a JSONObject
    JSONObject productJson = JSONObject.parseObject(productJsonString);
    
    // Retrieve the attribute value
    String attributeValue = productJson.getString(attributeName);
    // Do something with attributeValue here
} catch (JSONException e) {
    // Handle invalid JSON format error
    e.printStackTrace();
}

Key Notes:

  • Ensure Redis stores valid JSON: The value associated with productID in Redis must be a properly formatted JSON string. If it's not, the parse step will fail.
  • Alternative libraries: If you prefer Jackson instead of FastJSON, you can use ObjectMapper to parse the string:
    ObjectMapper mapper = new ObjectMapper();
    JSONObject productJson = mapper.readValue(productJsonString, JSONObject.class);
    
  • Resource management: Using try-with-resources ensures the Jedis connection is returned to the pool properly, preventing resource leaks.

内容的提问来源于stack exchange,提问作者vkaul11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:04:48