Let's
extract organization names, employee firstName, lastName and salary
from below json document.
{ "org": [{ "name": "Honeywell", "yrsOfExperience": 2.2 }, { "name": "IBM", "yrsOfExperience": 1.8 }], "empName": { "firstName": "Krishna", "lastName": "Rama" }, "salary": 80000.0 }
"$.empName.firstName":
Extract firstName from the document.
"$.empName.lastName":
Extract lastNam from the document.
"$.org[0].name":
Extract first organisation name
"$.org[1].name":
Extract second organisation name
"$"
represents root element.
Example
String
firstOrganization = JsonPath.read(json, "$.org[0].name");
String
secondOrganization = JsonPath.read(json, "$.org[1].name");
String
firstName = JsonPath.read(json, "$.empName.firstName");
String
lastName = JsonPath.read(json, "$.empName.lastName");
double
salary = JsonPath.read(json, "$.salary");
App.java
package com.sample.app; import com.jayway.jsonpath.JsonPath; public class App { public static void main(String[] args) { String json = "{\n" + " \"org\": [{\n" + " \"name\": \"Honeywell\",\n" + " \"yrsOfExperience\": 2.2\n" + " }, {\n" + " \"name\": \"IBM\",\n" + " \"yrsOfExperience\": 1.8\n" + " }],\n" + "\n" + " \"empName\": {\n" + " \"firstName\": \"Krishna\",\n" + " \"lastName\": \"Rama\"\n" + " },\n" + "\n" + " \"salary\": 80000.0\n" + "}"; String firstOrganization = JsonPath.read(json, "$.org[0].name"); String secondOrganization = JsonPath.read(json, "$.org[1].name"); String firstName = JsonPath.read(json, "$.empName.firstName"); String lastName = JsonPath.read(json, "$.empName.lastName"); double salary = JsonPath.read(json, "$.salary"); System.out.println("firstOrganization : " + firstOrganization); System.out.println("secondOrganization : " + secondOrganization); System.out.println("firstName : " + firstName); System.out.println("lastName : " + lastName); System.out.println("salary : " + salary); } }
Output
firstOrganization : Honeywell secondOrganization : IBM firstName : Krishna lastName : Rama salary : 80000.0
No comments:
Post a Comment