JsonPath selecting object field if multiple condition matches - java

{
"userName": "test"
"customer": {
"mode": "BANK",
"modeDetails": {
"accountNo": "12345678901001",
"walletId": "11324354#paypal"
}
}
}
I am using jsonpath to select accountNo if mode="BANK" or else if mode=WALLET then walletId should be selected. I tried expression $.customer.modeDetails[$.customer.mode=='BANK'].accountNo but it doesn't work. Please help me on this.

public static void main(String[] args) {
String jsonString = "{\r\n" +
" \"userName\": \"test\",\r\n" +
" \"customer\": {\r\n" +
" \"mode\": \"BANK\",\r\n" +
" \"modeDetails\": {\r\n" +
" \"accountNo\": \"12345678901001\",\r\n" +
" \"walletId\": \"11324354#paypal\"\r\n" +
" }\r\n" +
" }\r\n" +
"}";
DocumentContext docCtx = JsonPath.parse(jsonString);
JsonPath jsonPath = JsonPath.compile("$..[?(#.customer.mode==\"BANK\")].customer.modeDetails.accountNo");
List<String> accounts = docCtx.read(jsonPath);
System.out.println(accounts);
}
result
["12345678901001"]

Related

how to iterate json and convert into following json format in JAVA

How to iterate json in java. I wanted iterate elements inside payload, grab the first level and second level key and array value. I have converted the same in python. I'm new to java and wanted convert in java. Any help would be appreciated.
Python Code:
import os
import sys
import json
import datetime
def lambda_handler(event, context):
indata = event['payload']
outputDictionary = []
for i in indata:
for j in indata[i]:
for k in indata[i][j]:
outputDictionary.append(dict(source = i,code=j,version=k))
return outputDictionary
Input :
{
"payload": {
"gtl": {
"435185": [
"2019-11-27T14:34:32.368197Z"
]
},
"ptl": {
"A0947863": [
"2019-11-27T14:34:32.368197Z"
]
},
"mtl": {
"A0947863": [
"2019-11-27T14:34:32.368197Z",
"2021-04-27T06:13:12.841968Z"
]
}
}
}
Expected Output
[
{
"source": "gtl",
"code": "435185",
"version": "2019-11-27T14:34:32.368197Z"
},
{
"source": "ptl",
"code": "A0947863",
"version": "2019-11-27T14:34:32.368197Z"
},
{
"source": "mtl",
"code": "A0947863",
"version": "2019-11-27T14:34:32.368197Z"
},
{
"source": "mtl",
"code": "A0947863",
"version": "2021-04-27T06:13:12.841968Z"
}
]
SOLVED IN JAVA:
Java CODE:
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ParseJson {
public static void main(String[] args) {
String inputJson = "{\r\n" +
" \"payload\": {\r\n" +
" \"gtl\": {\r\n" +
" \"435185\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"ptl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"mtl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\",\r\n" +
" \"2021-04-27T06:13:12.841968Z\"\r\n" +
" ]\r\n" +
" }\r\n" +
" }\r\n" +
"}";
final JSONObject inputJSONOBject = new JSONObject(inputJson);
JSONObject jsonChildObject = (JSONObject)inputJSONOBject.get("payload");
Iterator iterator = jsonChildObject.keys();
while (iterator.hasNext()) {
String key = null;
while(iterator.hasNext()){
String source = (String)iterator.next();
JSONObject codeChildObject = jsonChildObject.getJSONObject(source);
Iterator iterator2 = codeChildObject.keys();
while(iterator2.hasNext()){
String code = (String)iterator2.next();
org.json.JSONArray jsonArray = codeChildObject.getJSONArray(code);
for(int i=0;i<jsonArray.length();i++){
System.out.println("Source:" + source);
System.out.println("CODE:" + code);
System.out.println("Version: "+jsonArray.get(i));
}
}
}
}
}
//System.out.println(inputJSONOBject);
}
You have done everything right except for that extra loop for the first iterator. Following is the complete working solution.
class ParseJson {
public static void main(String[] args) throws Exception {
String inputJson = "{\r\n" +
" \"payload\": {\r\n" +
" \"gtl\": {\r\n" +
" \"435185\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"ptl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"mtl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\",\r\n" +
" \"2021-04-27T06:13:12.841968Z\"\r\n" +
" ]\r\n" +
" }\r\n" +
" }\r\n" +
"}";
JSONArray output = convert(inputJson);
System.out.println(output.toString(5));
}
private static JSONArray convert(String inputJson) throws Exception {
final JSONObject inputJSONOBject = new JSONObject(inputJson);
JSONObject jsonChildObject = (JSONObject) inputJSONOBject.get("payload");
JSONArray outputArray = new JSONArray();
Iterator payloadIterator = jsonChildObject.keys();//gtl,ptl,mtl
while (payloadIterator.hasNext()) {
String source = (String) payloadIterator.next(); //gtl
JSONObject codeChildObject = jsonChildObject.getJSONObject(source);
Iterator codeIterator = codeChildObject.keys();//123, 456
while (codeIterator.hasNext()) {
String code = (String) codeIterator.next();//123
org.json.JSONArray jsonArray = codeChildObject.getJSONArray(code);// t1,t2,t3
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = new JSONObject();
object.put("source", source);
object.put("code", code);
object.put("version", jsonArray.get(i)); //t1
outputArray.put(object);
}
}
}
return outputArray;
}
}

java - replace string in JSON with json array of objects

I've a JSON:
{
"payment_intent": {
"amount": "Amount",
"currency_code": "840",
"invoice_number": "pay-automation-invoice-no-01",
"payment_intent_id": "pay-automation-return-intent-id-01",
"intent_reference_id": "pay-automation-intent-reference-id-01"
},
"payment_refundable_intents": {
"transactions": {
"sales": "pay-automation-sales"
}
}
}
Now, when I tried to replace string "pay-automation-sales" with JSONArray using
payloadJson = payloadJson.replaceAll("pay-automation-sales", salesString);
salesString is
[{"amount":"200.0","payment_intent_id":"29518150","tender_type":"cash","reference_id":"db79893a-9fe0-4391-91f8-fbc-cash-6c88-66db","intent_reference_id":"db79893a-9fe0-4391-91f8-fbc7945ce446","id":"000000893275","status":"Approved"},{"amount":"800.0","payment_intent_id":"29518150","tender_type":"cash","reference_id":"db79893a-9fe0-4391-91f8-fbc-cash-1d12-8466","intent_reference_id":"db79893a-9fe0-4391-91f8-fbc7945ce446","id":"000000893282","status":"Approved"}]
Here, payloadJson is of type String. The replaceAll works fine but actually I want to pass "sales" as an array of object in JSON. But it is getting passed like this and it's not a valid JSON format. Double quotes in value of sales key in JSON causes an issue I think.
"sales": "[{"amount":"200.0","payment_intent_id":"29518150","tender_type":"cash","reference_id":"db79893a-9fe0-4391-91f8-fbc-cash-6c88-66db","intent_reference_id":"db79893a-9fe0-4391-91f8-fbc7945ce446","id":"000000893275","status":"Approved"},{"amount":"800.0","payment_intent_id":"29518150","tender_type":"cash","reference_id":"db79893a-9fe0-4391-91f8-fbc-cash-1d12-8466","intent_reference_id":"db79893a-9fe0-4391-91f8-fbc7945ce446","id":"000000893282","status":"Approved"}]"
How do I replace string in JSON with valid JSON array of objects?
Since you're working with String objects here and not some form of JSON object model, when you did
payloadJson = payloadJson.replaceAll("pay-automation-sales", salesString);
it found the string
pay-automation-sales
within payloadJson and replaced it verbatin with the contents of salesString. Notice that you did NOT tell it to include the quotes in the original string in the part being replaced.
It should be
payloadJson = payloadJson.replaceAll("\"pay-automation-sales\"", salesString);
You would probably be better off using a real JSON library that understands JSON syntax and can manipulate the JSON as an in-memory document model.
Using Java String
public class StringDemo {
static final String originalJson = " {\n"
+ " \"payment_intent\": {\n"
+ " \"amount\": \"Amount\",\n"
+ " \"currency_code\": \"840\",\n"
+ " \"invoice_number\": \"pay-automation-invoice-no-01\",\n"
+ " \"payment_intent_id\": \"pay-automation-return-intent-id-01\",\n"
+ " \"intent_reference_id\": \"pay-automation-intent-reference-id-01\"\n"
+ " },\n"
+ " \"payment_refundable_intents\": {\n"
+ " \"transactions\": {\n"
+ " \"sales\": \"pay-automation-sales\"\n"
+ " }\n"
+ " }\n"
+ "}";
static final String originalArray = "[{\"amount\":\"200.0\",\"payment_intent_id\":\"29518150\",\"tender_type\":\"cash\",\"reference_id\":\"db79893a-9fe0-4391-91f8-fbc-cash-6c88-66db\",\"intent_reference_id\":\"db79893a-9fe0-4391-91f8-fbc7945ce446\",\"id\":\"000000893275\",\"status\":\"Approved\"},{\"amount\":\"800.0\",\"payment_intent_id\":\"29518150\",\"tender_type\":\"cash\",\"reference_id\":\"db79893a-9fe0-4391-91f8-fbc-cash-1d12-8466\",\"intent_reference_id\":\"db79893a-9fe0-4391-91f8-fbc7945ce446\",\"id\":\"000000893282\",\"status\":\"Approved\"}]";
public static void main(String[] args) {
String editedJson = originalJson.replaceAll("\"pay-automation-sales\"", originalArray);
System.out.println(editedJson);;
}
}
Using Jackson
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
public class JacksonDemo {
static final String originalJson = " {\n"
+ " \"payment_intent\": {\n"
+ " \"amount\": \"Amount\",\n"
+ " \"currency_code\": \"840\",\n"
+ " \"invoice_number\": \"pay-automation-invoice-no-01\",\n"
+ " \"payment_intent_id\": \"pay-automation-return-intent-id-01\",\n"
+ " \"intent_reference_id\": \"pay-automation-intent-reference-id-01\"\n"
+ " },\n"
+ " \"payment_refundable_intents\": {\n"
+ " \"transactions\": {\n"
+ " \"sales\": \"pay-automation-sales\"\n"
+ " }\n"
+ " }\n"
+ "}";
static final String originalArray = "[{\"amount\":\"200.0\",\"payment_intent_id\":\"29518150\",\"tender_type\":\"cash\",\"reference_id\":\"db79893a-9fe0-4391-91f8-fbc-cash-6c88-66db\",\"intent_reference_id\":\"db79893a-9fe0-4391-91f8-fbc7945ce446\",\"id\":\"000000893275\",\"status\":\"Approved\"},{\"amount\":\"800.0\",\"payment_intent_id\":\"29518150\",\"tender_type\":\"cash\",\"reference_id\":\"db79893a-9fe0-4391-91f8-fbc-cash-1d12-8466\",\"intent_reference_id\":\"db79893a-9fe0-4391-91f8-fbc7945ce446\",\"id\":\"000000893282\",\"status\":\"Approved\"}]";
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(originalJson);
JsonNode array = mapper.readTree(originalArray);
ObjectNode transactions = (ObjectNode) root.findValue("transactions");
transactions.set("sales", array);
String editedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);
System.out.println(editedJson);;
}
}

List of Json records

I have a list of json records, for instance:
[{“age”:27,”lastname”:”Robert “,”firstName”:”Rob”,”company”:”abc”},
{“age”:27,”lastname”:”Ashok “,”firstName”:”Bob”,”company”:”def”},
{“age”:27,”lastname”:”murali“,”firstName”:”Got”,”company”,”Ghori”}]
Write a method which takes lastName as parameter and based on that input I need to get only that particular record out and get it displayed
Your probleme is not well explained, you can try this solution (after correcting your string to be a real json content)
Using ObjectMapper you can read your string to transform it to an ArrayNode
public static void main(String[] args) throws IOException {
String json= "[\n" +
" {\n" +
" \"age\":27,\n" +
" \"lastname\":\"Robert \",\n" +
" \"firstName\":\"Rob\",\n" +
" \"company\":\"abc\"\n" +
" },\n" +
" {\n" +
" \"age\":27,\n" +
" \"lastname\":\"Ashok \",\n" +
" \"firstName\":\"Bob\",\n" +
" \"company\":\"def\"\n" +
" },\n" +
" {\n" +
" \"age\":27,\n" +
" \"lastname\":\"murali\",\n" +
" \"firstName\":\"Got\",\n" +
" \"company\":\"\"\n" +
" }\n" +
"]";
// example with murali
getLine(json, "murali");
}
private static String getLine(String json, String lastName) throws IOException {
ArrayNode rootNode = (ArrayNode) new ObjectMapper().readTree(json);
for(JsonNode jsonNode : rootNode) {
ObjectNode node = (ObjectNode)jsonNode;
String lastNameValue = node.get("lastname").textValue();
if(lastName.equals(lastNameValue)){
return jsonNode.toString();
}
}
return null;
}
the result for this example is :
{"age":27,"lastname":"murali","firstName":"Got","company":""}

Jsonpath to show children with dynamic names

I have this json data that I was to parse with jsonpath:
{
"kind": "tm:sys:hardware:hardwarestats",
"selfLink": "https://localhost/mgmt/tm/sys/hardware?ver\u003d11.5.4",
"entries": {
"https://localhost/mgmt/tm/sys/hardware/platform": {
"nestedStats": {
"entries": {
"https://localhost/mgmt/tm/sys/hardware/platform/0": {
"nestedStats": {
"entries": {
"baseMac": {
"description": "00:00ยง:00:00:00:00"
},
"biosRev": {
"description": "OBJ-0065-xx Build: 1.06.043.0 05/02/2014"
},
"marketingName": {
"description": "BIG-IP VPR-C2400"
},
"pvaVersion": {
"description": "20"
}
}
}
}
}
}
}
}
}
As you can see some parts consists of children named according to this:
https://[host]/path
I would like to be able to essentially ignore the host part by using a wildcard:
$.entries.https://*/mgmt/tm/sys/hardware/platform.nestedStats.entries.*.nestedStats.entries.marketingName.description
Note the wildcard replacing localhost (it differs depending on which host header is sent to the api endpoint).
I have no control over the server side. Any suggestion appreciated!
/Patrik
If you just want to get the values of those baseMac, biosRev descriptions without filtering path, this should be enough
public static void main(String[] args) {
String samplejson = "{\n" +
" \"kind\": \"tm:sys:hardware:hardwarestats\",\n" +
" \"selfLink\": \"https://localhost/mgmt/tm/sys/hardware?ver\\u003d11.5.4\",\n" +
" \"entries\": {\n" +
" \"https://localhost/mgmt/tm/sys/hardware/platform\": {\n" +
" \"nestedStats\": {\n" +
" \"entries\": {\n" +
" \"https://localhost/mgmt/tm/sys/hardware/platform/0\": {\n" +
" \"nestedStats\": {\n" +
" \"entries\": {\n" +
" \"baseMac\": {\n" +
" \"description\": \"00:00ยง:00:00:00:00\"\n" +
" },\n" +
" \"biosRev\": {\n" +
" \"description\": \"OBJ-0065-xx Build: 1.06.043.0 05/02/2014\"\n" +
" },\n" +
" \"marketingName\": {\n" +
" \"description\": \"BIG-IP VPR-C2400\"\n" +
" },\n" +
" \"pvaVersion\": {\n" +
" \"description\": \"20\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
Object baseMac = JsonPath.read(samplejson, "$.entries..nestedStats.entries.marketingName.description");
System.out.println(baseMac.toString());
}
But, if you want to read those descriptions w.r.t only certain paths, like you want to read only https://localhost/mgmt/tm/sys/hardware/platform/0 and NOT https://localhost/mgmt/tm/sys/hardware/platform/**1**, then solution should be something else.

How to parse the values present in JSON Array in this case

I am trying to Parse this JSON
{
"details": {
"Service Tax": [
{
"tax_order": 3,
"inclusive": [
{
"Discount": 1,
"Service Charge": 1
}
]
}
],
"VAT": [
{
"tax_order": 3,
"inclusive": [
{
"Discount": 1,
"Service Charge": 1,
"Item": 1
}
]
}
]
},
"vendor_id": 1
}
Is it possible to extract the fields for that value present in the array .
For example if it is Service Tax , i need to fetch the Discount and Service Charge
For example if it is VAT , i need to fetch the Discount , Service Charge and Item
package test;
import org.json.JSONArray;
import org.json.JSONObject;
public class Tester {
public static void main(String args[]) throws Exception
{
String json = "{\r\n" +
" \"details\": {\r\n" +
" \"Service Tax\": [\r\n" +
" {\r\n" +
" \"tax_order\": 3,\r\n" +
" \"inclusive\": [\r\n" +
" {\r\n" +
" \"Discount\": 1,\r\n" +
" \"Service Charge\": 1\r\n" +
" }\r\n" +
" ]\r\n" +
" }\r\n" +
" ],\r\n" +
" \"VAT\": [\r\n" +
" {\r\n" +
" \"tax_order\": 3,\r\n" +
" \"inclusive\": [\r\n" +
" {\r\n" +
" \"Discount\": 1,\r\n" +
" \"Service Charge\": 1,\r\n" +
" \"Item\": 1\r\n" +
" }\r\n" +
" ]\r\n" +
" }\r\n" +
" ]\r\n" +
" },\r\n" +
" \"vendor_id\": 1\r\n" +
"}";
String[] json_order = new String[]{"Service Tax", "VAT"};
JSONObject inputRqstJson = new JSONObject(json);
JSONObject details_json = inputRqstJson.getJSONObject("details");
for(String tax_name : json_order)
{
JSONArray tax_nameJarray = details_json.getJSONArray(tax_name);
System.out.println(tax_nameJarray);
}
}
}

Categories

Resources