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

基于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 traverseJson method handles both JSONObject and JSONArray types. 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 extractWeWantThis method catches ParseException for 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:49:13