Java JsonPath Tutorial: Parse JSON Data
In Java, you can use the third-party library json-path to parse JSON data. Here is a simple example:
import com.jayway.jsonpath.JsonPath;
public class JsonPathExample {
public static void main(String[] args) {
String json = "{\"name\": \"Alice\", \"age\": 30, \"pets\": [\"dog\", \"cat\"]}";
String name = JsonPath.read(json, "$.name");
int age = JsonPath.read(json, "$.age");
String pet1 = JsonPath.read(json, "$.pets[0]");
String pet2 = JsonPath.read(json, "$.pets[1]");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Pet 1: " + pet1);
System.out.println("Pet 2: " + pet2);
}
}
In the example above, first import the json-path library, then parse the JSON data using the JsonPath.read method. You can use path expressions like $.name to get specific field values in the JSON, or use $.pets[0] to retrieve elements in an array. Finally, output the parsed result.