溫馨提示×

java怎么遍歷json的key和value

小億
316
2023-12-15 22:43:31
欄目: 編程語言

在Java中遍歷JSON的key和value可以使用org.json庫或者com.fasterxml.jackson.databind庫。以下是兩種方法的示例:

使用org.json庫:

import org.json.JSONObject;

public class JsonExample {
    public static void main(String[] args) {
        String jsonStr = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

        JSONObject jsonObject = new JSONObject(jsonStr);
        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            System.out.println(key + ": " + value);
        }
    }
}

使用com.fasterxml.jackson.databind庫:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonExample {
    public static void main(String[] args) throws Exception {
        String jsonStr = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(jsonStr);
        jsonNode.fields().forEachRemaining(entry -> {
            String key = entry.getKey();
            JsonNode value = entry.getValue();
            System.out.println(key + ": " + value);
        });
    }
}

無論是使用org.json庫還是com.fasterxml.jackson.databind庫,都可以通過遍歷JSON對象的key集合來獲取對應的value值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女