Having trouble accessing fields of JSON using groovy - java

I'm trying to extract the information from an API response using groovy
I want to get to the info stored under the "res" key.
Something along the lines of body.measures.02:00:00:02:06:70.res
Can not figure out have to access this information without throwing a nullpointerexception.
"body":[ {
"_id":"70:ee:50:01:fe:96",
"place":{
"location":[
-70.863189,
42.273936
],
"altitude":26.154942,
"timezone":"America\/New_York"
},
"mark":12,
"measures":{
"02:00:00:02:06:70":{
"res":{
"1506611038":[
22,
66
]
},
"type":[
"temperature",
"humidity"
]
},
"06:00:00:01:97:28":{
"wind_strength":15,
"wind_angle":343,
"gust_strength":29,
"gust_angle":301,
"wind_timeutc":1506611083
},
"70:ee:50:01:fe:96":{
"res":{
"1506611086":[
1007.4
]
},
"type":[
"pressure"
]
}
},
"modules":[
"02:00:00:02:06:70",
"06:00:00:01:97:28"
],
"module_types":{
"02:00:00:02:06:70":"NAModule1",
"06:00:00:01:97:28":"NAModule2"
}
}
],
"status":"ok",
"time_exec":0.017483949661255,
"time_server":1506611446
}

body is an array with one element in your case, so you have to do body[0].measures.'02:00:00:02:06:70'.res, e. g. like
new groovy.json.JsonSlurper().parseText('''{"body":[ {
"_id":"70:ee:50:01:fe:96",
"place":{
"location":[
-70.863189,
42.273936
],
"altitude":26.154942,
"timezone":"America/New_York"
},
"mark":12,
"measures":{
"02:00:00:02:06:70":{
"res":{
"1506611038":[
22,
66
]
},
"type":[
"temperature",
"humidity"
]
},
"06:00:00:01:97:28":{
"wind_strength":15,
"wind_angle":343,
"gust_strength":29,
"gust_angle":301,
"wind_timeutc":1506611083
},
"70:ee:50:01:fe:96":{
"res":{
"1506611086":[
1007.4
]
},
"type":[
"pressure"
]
}
},
"modules":[
"02:00:00:02:06:70",
"06:00:00:01:97:28"
],
"module_types":{
"02:00:00:02:06:70":"NAModule1",
"06:00:00:01:97:28":"NAModule2"
}
}
],
"status":"ok",
"time_exec":0.017483949661255,
"time_server":1506611446
}}''').body[0].measures.'02:00:00:02:06:70'.res

Related

How to get json key values by another key value

I have a JSON output like this:
{
"items": [
{
"id": "1",
"name": "Anna",
"values": [
{
"code": "Latin",
"grade": 1
},
{
"code": "Maths",
"grade": 5
}
]
},
{
"id": "2",
"name": "Mark",
"values": [
{
"code": "Latin",
"grade": 5
},
{
"code": "Maths",
"grade": 5
}
]
}
]
}
I need to get field values for "name": "Anna". I am getting RestAssured Response and would like to use my beans to do that, but I can also use jsonPath() or jsonObject(), but I don't know how. I searched many topics but did not find anything.

Regex to replace key & value in JSON

I'm trying to remove the below key and valuefrom the JSON string in Java. I couldn't really crack the pattern. Can anyone help me find what I'm doing wrong here?
"appointment_request_id": "77bl5ii169daj0abqaowl0ggmnwxdk1219mug023", // (, included)
String newTransformedJsonString = jsonString.replaceAll("\"appointment_request_id\":\".*\",","");
I think I need to add a wildcard to make sure the starting and ending " for value are considered. I tried ?, surrounding the " as ["]. No luck.
The value will never be empty.
The value will have spaces trimmed
Assume the value can have any character
{
"appointment_request_id": "77bl5ii169daj0abqaowl0ggmnwxdk1219mug023",
"app_spec_version": "0.0.61-5",
"previous_invoice_ids": [
"18000-A-qa4wl0kvka",
"18101-A-y49daj0ppp"
],
"contracts": [
{
"name": "bcbs.patient",
"definitions": [
{
"base_path": "/patient/v1",
"swagger": {
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "patient-v1"
},
"basePath": "",
"tags": [
{
"name": "patient-v1",
"description": "PatientServiceResource"
}
],
"schemes": [
"http"
],
"webpages": {
"/patient/v1/insurace": {
"get": {
"tags": [
"patient-v1"
],
"summary": "Returnsanerror,butwaitsbeforedoingso.",
"operationId": "getInsurance",
"produces": [
"application/json"
],
"parameters": [
{
"name": "statusCode",
"in": "query",
"description": "",
"required": false,
"type": "integer",
"format": "int32"
}
]
}
}
}
}
}
]
}
]
}
This may be helpful.
How to make a regex to replace the value of a key in a json file

How to fetch values from nested JSON in JAVA using Jsonpath

Below is the JSON response, I have used JSONPath get() to retrieve value of totalContractAmout by using below path - subscriptionQuoteResponseDetails.customerQuoteDetails[0].billPlanQuoteDetails[0].serviceList[0].skuList[0].totalContractAmount
But this seems to be hard coded, is there any way I can make it generic using JAVA language.
{
"transactionId": "Transaction123",
"systemId": "AAA",
"userId": "User123",
"resultDate": "2019-11-23T12:52:16.400-06:00",
"resultCode": "100",
"resultMessage": "SUCCESS",
"subscriptionQuoteResponseDetails": {
"quoteDetailsStatusCode": 2,
"customerQuoteDetails": [
{
"customerId": "546789",
"buid": "111",
"billPlanQuoteDetails": [
{
"serviceList": [
{
"serviceType": "/service/",
"skuList": [
{
"skuId": "932125",
"productName": "DummyName",
"quantity": 4,
"totalContractAmount": 1728,
"rateCards": [
{
"productCadence": "M",
"cadenceAmount": 48
},
{
"productCadence": "F",
"cadenceAmount": 1728
}
]
}
]
}
]
}
]
}
]
}
}

Json query String for getting value with Condition

I want to get the value of vehicleCodeelement where vehicleLease is AS PER LAW OF ENFORCMENT.
Could someone please help me with JSON query ?
Please find JSON data below.
{
"StateOffers": [
[{
"vehicleCode": 242214214,
"vehiclePart": [{
"#type": "vehiclePart",
"segments": [{
"#type": "Segment"
"segmentOfferInformation": {
"vehicleMiles": 771,
"awardFare": false
},
"vehicleLease": "AS PER LAW OF ENFORCMENT"
}
],
"stops": 0
}
]
}, {
"vehicleCode": 242214214,
"vehiclePart": [{
"#type": "vehiclePart",
"segments": [{
"#type": "Segment"
"segmentOfferInformation": {
"vehicleMiles": 771,
"awardFare": false
},
"vehicleLease": "MY RULE MY WORLD"
}
],
"stops": 0
}
]
}
]
]
}
This is the expression I have tried:
$..vehicleCode[?($..vehicleLease=="AS PER LAW OF ENFORCMENT")

Parsing Json data giving ClassCastException

I am currently using the following JSON parser but keep getting the error Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject. How can I fix this, it has worked many times before.
ublic List<String> handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
List<String> result = new ArrayList<String>();
String JSONResponse = new BasicResponseHandler()
.handleResponse(response);
try {
// Get top-level JSON Object - a Map
JSONObject responseObject = (JSONObject) new JSONTokener(
JSONResponse).nextValue(); //Problem Line
JSONObject item1 = responseObject.getJSONObject("searchResult");
// Extract value of "Item" key -- a List
JSONArray items = item1
.getJSONArray("Item");
Below is what I'm looking to parse
{
"findItemsAdvancedResponse":[
{
"ack":[
"Success"
],
"version":[
"1.13.0"
],
"timestamp":[
"2015-02-24T18:43:51.778Z"
],
"searchResult":[
{
"#count":"100",
"item":[
{
"itemId":[
"381098176861"
],
"title":[
" Tokyo Laundry Women's Kenzie Sweatpants - Eclipse Blue - TP1"
],
"globalId":[
"EBAY-GB"
],
"subtitle":[
"FREE UK DELIVERY | DISPATCHED WITHIN 1 WORKING DAY"
],
"primaryCategory":[
{
"categoryId":[
"137085"
],
"categoryName":[
"Activewear"
]
}
],
"secondaryCategory":[
{
"categoryId":[
"155226"
],
"categoryName":[
"Hoodies & Sweats"
]
}
],
"galleryURL":[
"http:\/\/thumbs2.ebaystatic.com\/pict\/3810981768614040_1.jpg"
],
"viewItemURL":[
"http:\/\/www.ebay.co.uk\/itm\/Tokyo-Laundry-Womens-Kenzie-Sweatpants-Eclipse-Blue-TP1-\/381098176861?pt=LH_DefaultDomain_3&var="
],
"paymentMethod":[
"PayPal"
],
"autoPay":[
"true"
],
"location":[
"United Kingdom"
],
"country":[
"GB"
],
"shippingInfo":[
{
"shippingServiceCost":[
{
"#currencyId":"GBP",
"__value__":"0.0"
}
],
"shippingType":[
"Free"
],
"shipToLocations":[
"AU",
"Europe"
]
}
],
"sellingStatus":[
{
"currentPrice":[
{
"#currencyId":"GBP",
"__value__":"14.99"
}
],
"convertedCurrentPrice":[
{
"#currencyId":"GBP",
"__value__":"14.99"
}
],
"sellingState":[
"Active"
],
"timeLeft":[
"P25DT14H10M23S"
]
}
],
"listingInfo":[
{
"bestOfferEnabled":[
"false"
],
"buyItNowAvailable":[
"false"
],
"startTime":[
"2014-12-22T08:49:14.000Z"
],
"endTime":[
"2015-03-22T08:54:14.000Z"
],
"listingType":[
"FixedPrice"
],
"gift":[
"false"
]
}
],
"galleryPlusPictureURL":[
"http:\/\/galleryplus.ebayimg.com\/ws\/web\/381098176861_1_1_1.jpg"
],
"condition":[
{
"conditionId":[
"1000"
],
"conditionDisplayName":[
"New with tags"
]
}
],
"isMultiVariationListing":[
"true"
],
"topRatedListing":[
"false"
]
},
{
"itemId":[
"131321072184"
],
"title":[
"Brave Soul Women's Dallas Parka - Mulberry - DD6 - Size 8-16"
],
"globalId":[
"EBAY-GB"
],
"subtitle":[
"FREE UK DELIVERY | DISPATCHED WITHIN 1 WORKING DAY"
],
"primaryCategory":[
{
"categoryId":[
"137085"
],
"categoryName":[
"Activewear"
]
}
],
"secondaryCategory":[
{
"categoryId":[
"63862"
],
"categoryName":[
"Coats & Jackets"
]
}
],
"galleryURL":[
"http:\/\/thumbs1.ebaystatic.com\/pict\/1313210721844040_3.jpg"
],
"viewItemURL":[
"http:\/\/www.ebay.co.uk\/itm\/Brave-Soul-Womens-Dallas-Parka-Mulberry-DD6-Size-8-16-\/131321072184?pt=LH_DefaultDomain_3&var="
],
"paymentMethod":[
"PayPal"
],
"autoPay":[
"true"
],
"location":[
"United Kingdom"
],
"country":[
"GB"
],
"shippingInfo":[
{
"shippingServiceCost":[
{
"#currencyId":"GBP",
"__value__":"0.0"
}
],
"shippingType":[
"Free"
],
"shipToLocations":[
"AU",
"Europe"
]
}
],
"sellingStatus":[
{
"currentPrice":[
{
"#currencyId":"GBP",
"__value__":"19.99"
}
],
"convertedCurrentPrice":[
{
"#currencyId":"GBP",
"__value__":"19.99"
}
],
"sellingState":[
"Active"
],
"timeLeft":[
"P15DT14H57M21S"
]
}
],
"listingInfo":[
{
"bestOfferEnabled":[
"false"
],
"buyItNowAvailable":[
"false"
],
"startTime":[
"2014-10-13T09:36:12.000Z"
],
"endTime":[
"2015-03-12T09:41:12.000Z"
],
"listingType":[
"FixedPrice"
],
"gift":[
"false"
]
}
],
"galleryPlusPictureURL":[
"http:\/\/galleryplus.ebayimg.com\/ws\/web\/131321072184_1_5_1.jpg"
],
"condition":[
{
"conditionId":[
"1000"
],
"conditionDisplayName":[
"New with tags"
]
}
],
"isMultiVariationListing":[
"true"
],
"topRatedListing":[
"false"
]
},
Why do you need a JSONTokener? This is much easier:
JSONObject responseObject = new JSONObject(JSONResponse);
JSONArray main = responseObject.getJSONArray("findItemsAdvancedResponse");
JSONObject result = main.getJSONObject(0).getJSONArray("searchResult").getJSONObject(0);
JSONArray items = result.getJSONArray("item");
Your nextValue() method must be returning a String, which you are then trying to cast to a JSONObject. I would start by splitting the statement up into smaller statements to help isolate the issue. You are instantiating a new object, calling a method on it, and type casting all on the same line. That makes code harder to debug.
JSONTokener tokener = new JSONTokener(JSONResponse);
Object obj = tokener.nextValue();
if(obj.getClass().equals(JSONObject.class))
{
JSONObject responseObject = (JSONObject)obj;
}
else
{
System.out.println("Not a JSONObject");
}

Categories