在 Json 响应中获取所有 Parent 和 Child 的名称

Get all Parent and Child Of Names in Json Resposne

我想使用 Rest Assured Java

一个一个地迭代 Response Child
public void preemptivve() throws ParseException {   
        RequestSpecification request = RestAssured.given()
                .contentType("application/x-www-form-urlencoded; charset=utf-8")
                .formParam("grant_type", "client_credentials");
        Headers header = new Headers(BaseClass.list);
        request.headers(header);
        Response response = request.given().when().post("/getclientdetails");       
        response.then().assertThat().body("size()", is(4));
        
    
        String jsonString=response.asString();
        String accesstoken=JsonPath.from(jsonString).get("access_token");
        System.out.println(jsonString);
        System.out.println(accesstoken);
        
        org.testng.Assert.assertEquals(response.getStatusCode(), 200);  
        
        
    ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(reponse.asString());
        Iterator<String> fieldNames = jsonNode.fieldNames();

        while(fieldNames.hasNext()) {
            String fieldName = fieldNames.next();
            JsonNode field = jsonNode.get(fieldName);
            System.out.println(fieldName);
            System.out.println(field);
            
        }

    }

我正在获取 parent 个元素..

例如,

"metadata": {
        "msgLst": [
            {
                "code": "00",
                "text": "SUCCESS"
            }
        ]
    }

我正在获取元数据,但我还需要 msgLst、代码和文本。如何获取这些信息..

我需要通过迭代来验证响应元素是否正确

我不确定你的实际目标是什么,但如果你想使用 jackson 获取 json 对象的所有键,那么这段代码可能适合你。

private List<String> getKeys(JsonNode node, List<String> allKeys) {
    Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
    while (fields.hasNext()) {
        Map.Entry<String, JsonNode> next = fields.next();
        allKeys.add(next.getKey());
        JsonNode value = next.getValue();
        if (value.isObject()) {
            getKeys(value, allKeys);
        }
        if (value.isArray()) {
            if (value.size() > 0) {
                JsonNode jsonNode = value.get(0);
                getKeys(jsonNode, allKeys);
            }
        }
    }
    return allKeys;
}

我用你的样本测试过json:

@Test
void SO_69436972() throws JsonProcessingException {
    String json = "{\n" +
            "  \"metadata\": {\n" +
            "    \"msgLst\": [\n" +
            "      {\n" +
            "        \"code\": \"00\",\n" +
            "        \"text\": \"SUCCESS\"\n" +
            "      }\n" +
            "    ]\n" +
            "  }\n" +
            "}";

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonNode = objectMapper.readTree(json);
    List<String> keyList = new ArrayList<>();
    System.out.println(getKeys(jsonNode, keyList));
}
[metadata, msgLst, code, text]