如何使用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 aString(the JSON data stored in Redis), but you're trying to assign it directly to aJSONObjectreference—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
productIDin 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
ObjectMapperto parse the string:ObjectMapper mapper = new ObjectMapper(); JSONObject productJson = mapper.readValue(productJsonString, JSONObject.class); - Resource management: Using
try-with-resourcesensures the Jedis connection is returned to the pool properly, preventing resource leaks.
内容的提问来源于stack exchange,提问作者vkaul11
相关产品推荐
相关产品推荐

