How to iterate through a JSON string in Java?
In Java, you can use JSON libraries like Jackson or Gson to parse and handle JSON strings. Here is an example of traversing a JSON string using the Jackson library.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonTraversalExample {
public static void main(String[] args) {
String jsonString = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}";
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);
// 遍历JSON对象的每个字段
jsonNode.fields().forEachRemaining(entry -> {
String key = entry.getKey();
JsonNode value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
In the code above, the JSON string is parsed into a JsonNode object using the ObjectMapper class. Afterwards, the fields() method can be used to loop through each field in the JsonNode object. In this example, the getKey() and getValue() methods are used to retrieve the key and value of each field.
Please note, this example is only suitable for simple JSON strings. If the JSON string has nested structures or arrays, handle them accordingly.