Saturday, 7 September 2019

JsonPath: Parse the document before querying


In my previous post, I explained how to extract the information from a json document using 'JsonPath.read()' method. If you want to extract the data once this is OK. In case you need to extract other parts of the data as well this is not the way to go since the document will be parsed every time you call JsonPath.read(...). To avoid the problem you can parse the json first.

Example
Object jsonDocument = Configuration.defaultConfiguration().jsonProvider().parse(json);

String firstOrganization = JsonPath.read(jsonDocument, "$.org[0].name");
String secondOrganization = JsonPath.read(jsonDocument, "$.org[1].name");
String firstName = JsonPath.read(jsonDocument, "$.empName.firstName");
String lastName = JsonPath.read(jsonDocument, "$.empName.lastName");
double salary = JsonPath.read(jsonDocument, "$.salary");

Input
{
 "org": [{
  "name": "Honeywell",
  "yrsOfExperience": 2.2
 }, {
  "name": "IBM",
  "yrsOfExperience": 1.8
 }],

 "empName": {
  "firstName": "Krishna",
  "lastName": "Rama"
 },

 "salary": 80000.0
}


App.java
package com.sample.app;

import com.jayway.jsonpath.Configuration;
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" + 
    "}";

  Object jsonDocument = Configuration.defaultConfiguration().jsonProvider().parse(json);
  
  String firstOrganization = JsonPath.read(jsonDocument, "$.org[0].name");
  String secondOrganization = JsonPath.read(jsonDocument, "$.org[1].name");
  String firstName = JsonPath.read(jsonDocument, "$.empName.firstName");
  String lastName = JsonPath.read(jsonDocument, "$.empName.lastName");
  double salary = JsonPath.read(jsonDocument, "$.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



Previous                                                    Next                                                    Home

No comments:

Post a Comment