x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    JsonPath Java example

    Like XPath is used to extract data from a XML document similarly, JsonPath is used to extract data from a JSON document. The root of a JSON document is identified by using ($) character.

    In this example we will show how to use JsonPath to extract content from a JSON document.

    First you need to download below dependency

    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>2.0.0</version>
    </dependency>
    

    1) Extract value from JSON at root level

    In below example we find id element which is at the root level. Root level elements can be found using "$" character. We also search for first element of subjects arrays using "$.subjects[0]"

    package json;
    
    import java.util.List;
    
    import com.jayway.jsonpath.Criteria;
    import com.jayway.jsonpath.Filter;
    import com.jayway.jsonpath.JsonPath;
    
    
    public class JsonPathTest {
        public static void main(String[] args) {
            String json = "{\"id\":12345, \"studentname\":\"James Anderson\", \"age\":35,"
                + " \"subjects\":[\"Computer Science\", \"Physics\"]}";
    
            Integer id = JsonPath.read(json, "$.id");
            System.out.println(id);
            String subject = JsonPath.read(json, "$.subjects[0]");
            System.out.println(subject);
    		
        }
    } 

    Console Output :

    12345
    Computer Science   

    2) Using Predicates to Filter Items

    We can also use predicates to filter an element in JSON. In below example, we will filter out students whose age is more than 30 years.

    package json;
    
    import java.util.List;
    
    import com.jayway.jsonpath.Criteria;
    import com.jayway.jsonpath.Filter;
    import com.jayway.jsonpath.JsonPath;
    
    
    public class JsonPathTest {
    	public static void main(String[] args) {
    			
            String json = "{ \"students\" : [{\"id\":12345,	 \"name\":\"James Anderson\", \"age\":25,
                    + \"subjects\":[\"computer science\",\"physics\"] }, "
                    + "{\"id\":12346, \"name\":\"Keanu Reeves\", \"age\":35,
                    + \"subjects\":[\"computer science\",\"physics\"] } ]	}";
            List<Object> names = JsonPath.read(json, "$.students[*].name");
            System.out.println(names);
    		
            Filter filter =	Filter.filter(Criteria.where("age").lt(30));
            String expr = "$['students'][?].name";
            names = JsonPath.read(json, expr, filter);
            System.out.println(names);
        }
    } 

    Console Output :

    ["James Anderson","Keanu Reeves"]
    ["James Anderson"]