基于org.json.simple自动提取JSON中指定字段weWantThis的值
Recursively Extract "weWantThis" from Arbitrary JSON with org.json.simple
Got it, when dealing with completely unknown and dynamic JSON structures, the only reliable way to track down that elusive "weWantThis" field is to recursively traverse every node in the JSON tree. Here's a straightforward implementation using org.json.simple that will dig through objects, arrays, and nested layers until it finds the field—or returns null if it doesn't exist.
Full Code Implementation
import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class JsonExtractor { public static Object extractWeWantThis(String jsonString) { JSONParser parser = new JSONParser(); try { Object jsonRoot = parser.parse(jsonString); return traverseJson(jsonRoot); } catch (ParseException e) { // Handle invalid JSON input e.printStackTrace(); return null; } } private static Object traverseJson(Object jsonNode) { // Check if current node is a JSONObject if (jsonNode instanceof JSONObject) { JSONObject jsonObj = (JSONObject) jsonNode; // First, check if this object directly contains our target field if (jsonObj.containsKey("weWantThis")) { return jsonObj.get("weWantThis"); } // If not, iterate through all key-value pairs and recurse into each value for (Object key : jsonObj.keySet()) { Object value = jsonObj.get(key); Object result = traverseJson(value); if (result != null) { return result; } } } // Check if current node is a JSONArray else if (jsonNode instanceof JSONArray) { JSONArray jsonArr = (JSONArray) jsonNode; // Iterate through each element in the array and recurse for (Object element : jsonArr) { Object result = traverseJson(element); if (result != null) { return result; } } } // If it's a primitive type (string, number, boolean) or null, no need to check further return null; } // Example usage to test the logic public static void main(String[] args) { String nestedSampleJson = "{\"level1\": {\"level2\": [{\"weWantThis\": \"Found me!\"}, {\"otherField\": \"nope\"}]}}"; Object result = extractWeWantThis(nestedSampleJson); System.out.println("Extracted value: " + result); // Outputs "Found me!" String noTargetJson = "{\"foo\": \"bar\", \"baz\": [1, 2, 3]}"; result = extractWeWantThis(noTargetJson); System.out.println("Extracted value: " + result); // Outputs null } }
Key Details Explained
- Recursive Traversal: The
traverseJsonmethod handles bothJSONObjectandJSONArraytypes. It prioritizes checking the current object for the target field first—if found, it returns the value immediately to avoid unnecessary work. - Early Termination: As soon as the field is located in any nested level, the method stops traversing and returns the value right away.
- Error Handling: The
extractWeWantThismethod catchesParseExceptionfor invalid JSON input and returns null in that scenario. - Primitive Type Handling: Any non-object/non-array nodes (like strings, numbers, booleans) are skipped since they can't contain the target field.
This approach works no matter how deep or chaotic the JSON structure is—whether your target lives in a top-level object, nested inside multiple layers, or hidden within an array element.
内容的提问来源于stack exchange,提问作者user6671584
相关产品推荐
相关产品推荐

