Parsing JSON data using GSON api - json

I have a JSON data and able to get the JSON data into a string.
I wish to get a json array from the root object one by one (using a loop if many are there)
The returned object must be of type "com.google.gson.JsonObject" as another method takes this object as input to get me the attribute values.
my json looks like this:
I would be needing the json array in "Resources" -
{
"totalResults": 2,
"startIndex": 1,
"schemas": [
"urn:ietf:params:scim:api:messages:2.0:ListResponse"
],
"Resources": [
{
"owner": {},
"application": {
"displayName": "Non Auth App",
"value": "4028b88168fa3d38016900d1759405a6",
"$ref": "http://localhost:8080/identityiq/scim/v2/Applications/4028b88168fa3d38016900d1759405a6"
},
"meta": {
"created": "2019-03-22T18:40:30.505+05:30",
"location": "http://localhost:8080/identityiq/scim/v2/Entitlements/297eff8a699f8b3a0169a5863769008b",
"version": "W/\"1553260230505\"",
"resourceType": "Entitlement"
},
"schemas": [
"urn:ietf:params:scim:schemas:sailpoint:1.0:Entitlement"
],
"displayableName": "reader",
"aggregated": false,
"id": "297eff8a699f8b3a0169a5863769008b",
"requestable": true,
"attribute": "Privileges",
"type": "Entitlement",
"descriptions": [],
"value": "reader"
},
{
"owner": {},
"application": {
"displayName": "Non Auth App",
"value": "4028b88168fa3d38016900d1759405a6",
"$ref": "http://localhost:8080/identityiq/scim/v2/Applications/4028b88168fa3d38016900d1759405a6"
},
"meta": {
"created": "2019-03-18T19:11:47.912+05:30",
"location": "http://localhost:8080/identityiq/scim/v2/Entitlements/297eff8a6990fc49016991096d08001e",
"version": "W/\"1552916507912\"",
"resourceType": "Entitlement"
},
"schemas": [
"urn:ietf:params:scim:schemas:sailpoint:1.0:Entitlement"
],
"displayableName": "admin",
"aggregated": false,
"id": "297eff8a6990fc49016991096d08001e",
"requestable": true,
"attribute": "Privileges",
"type": "Entitlement",
"descriptions": [],
"value": "admin"
}
]
}
Any help is appreciated.

Related

Get Object from http get API result

I know question has already asked but I can't do it with my get result.
My service get data from API return this kind of result :
{
"nhits": 581,
"parameters": {
"dataset": "communes-belges-2019",
"rows": 1,
"start": 0,
"facet": [
"niscode",
"region",
"nis_code_region"
],
"format": "json",
"timezone": "UTC"
},
"records": [
{
"datasetid": "communes-belges-2019",
"recordid": "65d40b7bc42f766b4fdb04c4a985766dc8b51717",
"fields": {
"shape_area": 79397718.576,
"mun_name_upper_fr": "ÉTALLE",
"arr_name_fr": "Virton",
"region": "Région wallonne",
"niscode": "85009",
"mun_off_language": "FR",
"geo_shape": {
"coordinates": [
[
[
5.678490965,
49.687217222
],
[
5.678462422,
49.6873304
]
]
],
"type": "Polygon"
},
"prov_name_fr": "Luxembourg",
"namefre": "Étalle",
"nom_commune": "Étalle",
"nis_code_region": "03000",
"mun_name_fr": "Étalle",
"reg_name_fr": "Région wallonne",
"mun_area_code": "BEL",
"modifdate": "2007-01-05",
"mun_type": "Commune/Gemeente/Gemeinde",
"mun_name_lower_fr": "étalle",
"prov_code": "80000",
"year": "2021-01-01",
"geo_point_2d": [
49.6639160352,
5.60896600843
]
},
"geometry": {
"type": "Point",
"coordinates": [
5.60896600843,
49.6639160352
]
},
"record_timestamp": "2019-05-24T09:44:14.333000+00:00"
}
],
"facet_groups": [
{
"name": "niscode",
"facets": [
{
"name": "11001",
"count": 1,
"state": "displayed",
"path": "11001"
},
{
"name": "33021",
"count": 1,
"state": "displayed",
"path": "33021"
},
{
"name": "33029",
"count": 1,
"state": "displayed",
"path": "33029"
},
{
"name": "33037",
"count": 1,
"state": "displayed",
"path": "33037"
}
]
},
{
"name": "region",
"facets": [
{
"name": "Région flamande",
"count": 299,
"state": "displayed",
"path": "Région flamande"
},
{
"name": "Région wallonne",
"count": 262,
"state": "displayed",
"path": "Région wallonne"
},
{
"name": "Région de Bruxelles-Capitale",
"count": 19,
"state": "displayed",
"path": "Région de Bruxelles-Capitale"
}
]
},
{
"name": "nis_code_region",
"facets": [
{
"name": "02000",
"count": 299,
"state": "displayed",
"path": "02000"
},
{
"name": "03000",
"count": 262,
"state": "displayed",
"path": "03000"
},
{
"name": "01000",
"count": 19,
"state": "displayed",
"path": "01000"
}
]
}
]
}
For the moment my service get data like this :
getProvinces(): Observable<any[]>{
return this._http.get<any>(this.apiProvinces)
.pipe(
map((response: any) => response.records as any[]),
catchError(this.handleError)
)
}
It returns a Observable<any[]> but I would like to get an object.
Therefore I defined a class with the below properties.
export class Record{
region : string;
nom_commune : string;
prov_name_fr: string;
records?: [];
constructor(reg: string, commune: string, prov: string) {
this.region = reg;
this.nom_commune = commune;
this.prov_name_fr = prov;
}
}
To reach that I try by replacing any[] by Record[] like below but it doesn't work.
getProvinces(): Observable<Record[]>{
return this._http.get<Record[]>(this.apiProvinces)
.pipe(
map(response => response as Record[]),
catchError(this.handleError)
)
}
In my component I defined an Observable<Record[]> like this :
public results$!: Observable<Record[]>;
And call the service like this :
this.results$ = this.apiService.getProvinces();
And try to see content in the html part:
<div *ngFor="let p of (results$ | async)">
{{p | json}}
</div>
I have the following error message : "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."
And can't access to my object.
Any suggestions is helpfull because. I'm absolutely new to ANgular.
Thanks
When you create an observable, you don't actually make a request to your api. To make the request and get the data from the observable, you need to subscribe.
this.apiService.getProvinces().subscribe((res) => (this.results = res));
This will execute the get request and return your data to the callback function. Get requests are finite observables, so you don't need to unsubscribe, but you will need to subscribe again if you want to make another request.

Update a Contentful post using PUT request via Postman

I'm trying to update a Contentful entry using Postman.
What I did:
In Contentful space, I created a test post to play with.
Went to Settings - API Keys - Content management tokens and generated a Personal access token
Created a GET request in Postman, passing space ID, master environment, and ID of the test post:
https://cdn.contentful.com/spaces/{spaceID}i/environments/master/entries?sys.id={postID}
I also sent authorisation header with content delivery token.
The GET request goes successfully and I'm able to copy the JSON object-response.
{
"sys": {
"type": "Array"
},
"total": 1,
"skip": 0,
"limit": 100,
"items": [
{
"metadata": {
"tags": []
},
"sys": {
"space": {
"sys": {
"type": "Link",
"linkType": "Space",
"id": "d9r4mg123x4v"
}
},
"id": "2Fwow39hxxx1bvMkjpsyV9",
"type": "Entry",
"createdAt": "2021-11-10T14:00:11.935Z",
"updatedAt": "2021-11-10T14:06:51.393Z",
"environment": {
"sys": {
"id": "master",
"type": "Link",
"linkType": "Environment"
}
},
"revision": 3,
"contentType": {
"sys": {
"type": "Link",
"linkType": "ContentType",
"id": "hotelInfo"
}
},
"locale": "en-US"
},
"fields": {
"name": "Test entry",
"slug": "test-entry",
"address": "Lviv",
"cityName": "Lviv",
"phone": "+380931231212",
"coordinates": {
"lon": -115.302,
"lat": 36.18709
},
"dog": "100",
"cat": "100",
"delivery": "100",
"photo": [
{
"sys": {
"type": "Link",
"linkType": "Asset",
"id": "2hSnYhQDJzU99NvlsYdk3k"
}
}
],
"additionalInfo": {
"data": {},
"content": [
{
"data": {},
"content": [
{
"data": {},
"marks": [],
"value": "Test",
"nodeType": "text"
}
],
"nodeType": "paragraph"
}
],
"nodeType": "document"
},
"featuredHotel": true,
"phoneClicks": 1
}
}
],
"includes": {
"Asset": [
{
"metadata": {
"tags": []
},
"sys": {
"space": {
"sys": {
"type": "Link",
"linkType": "Space",
"id": "d9r4mg123x4v"
}
},
"id": "2hSnYhQDJzU99NvlsYdk3k",
"type": "Asset",
"createdAt": "2021-11-10T13:59:59.954Z",
"updatedAt": "2021-11-10T13:59:59.954Z",
"environment": {
"sys": {
"id": "master",
"type": "Link",
"linkType": "Environment"
}
},
"revision": 1,
"locale": "en-US"
},
"fields": {
"title": "JS",
"description": "Lorem Ipsum",
"file": {
"url": "//images.ctfassets.net/d9r4mg123x4v/2hSnYhQDJzU99NvlsYdk3k/6fbabc7be7f4b28dc8b7deadd9892205/JS.png",
"details": {
"size": 23078,
"image": {
"width": 1024,
"height": 1024
}
},
"fileName": "JS.png",
"contentType": "image/png"
}
}
}
]
}
}
Now I want to create PUT request to send the updated JSON to the Contentful.
I paste the JSON I got as a response from GET request.
I change one of the values:
"name": "Test entry"
to
"name": "Test entry 123"
I send PUT request to https://api.contentful.com/spaces/{spaceID}/environments/master/entries/{postID}
The Authorisation header contains the Personal access token I generated before.
The X-Contentful-Version header contains the version of the post, can be found in post details
When I send this request, I get JSON response with an empty "fields": {}
{
"metadata": {
"tags": []
},
"sys": {
"space": {
"sys": {
"type": "Link",
"linkType": "Space",
"id": "d9r4mg123x4v"
}
},
"id": "2Fwow39hxxx1bvMkjpsyV9",
"type": "Entry",
"createdAt": "2021-11-10T13:57:10.882Z",
"updatedAt": "2021-11-11T10:58:39.480Z",
"environment": {
"sys": {
"id": "master",
"type": "Link",
"linkType": "Environment"
}
},
"publishedVersion": 13,
"publishedAt": "2021-11-10T14:06:51.393Z",
"firstPublishedAt": "2021-11-10T14:00:11.935Z",
"createdBy": {
"sys": {
"type": "Link",
"linkType": "User",
"id": "4123123123zOn3MkhuVB"
}
},
"updatedBy": {
"sys": {
"type": "Link",
"linkType": "User",
"id": "4123123123zOn3MkhuVB"
}
},
"publishedCounter": 3,
"version": 23,
"publishedBy": {
"sys": {
"type": "Link",
"linkType": "User",
"id": "4123123123zOn3MkhuVB"
}
},
"contentType": {
"sys": {
"type": "Link",
"linkType": "ContentType",
"id": "hotelInfo"
}
}
},
"fields": {}
}
And in Contentful Admin area, all the fields of the post become empty.
Contentful documentation says:
Contentful doesn't merge changes made to content, so when updating
content, you need to send the entire body of an entry. If you update
content with a subset of properties, you will lose all existing
properties not included in that update.
You should always update resources in the following order:
Fetch current resource.
Make changes to the current resource.
Update the resource by passing the changed resource along with current version number.
This way no unseen changes are overridden and unexpected conflicts are
unlikely to occur.
Note: You can't update any of the sys property fields, including
sys.id.
...so, I guess, I'm doing everything right - taking the post, editing data and sending updated post back.
I tried editing my JSON data to send it without sys fields, but no luck.
I'm stuck, anyone has any ideas what should I proceed with?
Thanks to #whitep4nth3r I was able to solve the problem.
I needed to GET data from the same source I'm trying to PUT it to.
The Authorisation header needed to be replaced with the Personal access token used for PUT request.

Integromat - Dynamically render spec of a collection from an rpc

I am trying to dynamically render a spec (Specification) of a collection from an RPC. Can't get it to work. Here I have attached the code of both 'module->mappable parameters' and the 'remote procedure->communication' here.
module -> mappable parameters
[
{
"name": "birdId",
"type": "select",
"label": "Bird Name",
"required": true,
"options": {
"store": "rpc://selectbird",
"nested": [
{
"name": "variables",
"type": "collection",
"label": "Bird Variables",
"spec": [
"rpc://birdVariables"
]
}
]
}
}
]
remote procedure -> communication
{
"url": "/bird/get-variables",
"method": "POST",
"body": {
"birdId": "{{parameters.birdId}}"
},
"headers": {
"Authorization": "Apikey {{connection.apikey}}"
},
"response": {
"iterate":{
"container": "{{body.data}}"
},
"output": {
"name": "{{item.name}}",
"label": "{{item.label}}",
"type": "{{item.type}}"
}
}
}
Thanks in advance.
Just tried the following and it worked. According to Integromat's Docs you can use the wrapper directive for the rpc like so:
{
"url": "/bird/get-variables",
"method": "POST",
"body": {
"birdId": "{{parameters.birdId}}"
},
"headers": {
"Authorization": "Apikey {{connection.apikey}}"
},
"response": {
"iterate":"{{body.data}}",
"output": {
"name": "{{item.name}}",
"label": "{{item.label}}",
"type": "{{item.type}}"
},
"wrapper": [{
"name": "variables",
"type": "collection",
"label": "Bird Variables",
"spec": "{{output}}"
}]
}
}
Your mappable parameters would then look like:
[
{
"name": "birdId",
"type": "select",
"label": "Bird Name",
"required": true,
"options": {
"store": "rpc://selectbird",
"nested": "rpc://birdVariables"
}
}
]
Needing this myself. Pulling in custom fields that have different types but would like them all to show for the user to update customs fields or when creating a contact be able to update them. Not sure if best to have them all show or have a select drop down then let the user use the map for more than one.
Here is my response from a Get for custom fields. Could you show how my code should look. Got little confused as usualy look for add a value in the output and do you need two separate RPC's in integromat? Noticed your store and nested were different.
{
"customFields": [
{
"id": "5sCdYXDx5QBau2m2BxXC",
"name": "Your Experience",
"fieldKey": "contact.your_experience",
"dataType": "LARGE_TEXT",
"position": 0
},
{
"id": "RdrFtK2hIzJLmuwgBtAr",
"name": "Assisted by",
"fieldKey": "contact.assisted_by",
"dataType": "MULTIPLE_OPTIONS",
"position": 0,
"picklistOptions": [
"Tom",
"Jill",
"Rick"
]
},
{
"id": "uyjmfZwo0PCDJKg2uqrt",
"name": "Is contacted",
"fieldKey": "contact.is_contacted",
"dataType": "CHECKBOX",
"position": 0,
"picklistOptions": [
"I would like to be contacted"
]
}
]
}

Parsing Git Json with Regular Express

I am taking a Github json file and parsing it with Java's regular expression library JsonPath. I am having a problem parsing arrays that do not have labels.
I need to send a email every time a particular file is changed in our repository.
Here is the Git Json:
{
"trigger": "push",
"payload": {
"type": "GitPush",
"before": "xxxxxxxx",
"after": "yyyyyyyy",
"branch": "branch-name",
"ref": "refs/heads/branch-name",
"repository": {
"id": 42,
"name": "repo",
"title": "repo",
"type": "GitRepository"
},
"beanstalk_user": {
"type": "Owner",
"id": 42,
"login": "username",
"email": "user#example.org",
"name": "Name Surname"
},
"commits": [
{
"type": "GitCommit",
"id": "ffffffff",
"message": "Important changes.",
"branch": "branch-name",
"author": {
"name": "Name Surname",
"email": "user#example.org"
},
"beanstalk_user": {
"type": "Owner",
"id": 42,
"login": "username",
"email": "user#example.org",
"name": "Name Surname"
},
"changed_files": {
"added": [
"NEWFILE",
],
"deleted": [
"Gemfile",
"NEWFILE"
],
"modified": [
"README.md",
"NEWFILE"
],
"copied": [
]
},
"changeset_url": "https://subdomain.github.com/repository-name/changesets/ffffffff",
"committed_at": "2014/08/18 13:30:29 +0000",
"parents": [
"afafafaf"
]
}
]
}
}
This is the expression I am using: to get the commits
$..changed_files
This return the whole changed files part but I can not explicitly choose the name "NEWFILE"
I tried
$..changed_files.*[?(#.added == "NEWFILE")]
$..changed_files.*[?(#.*== "NEWFILE")]
It just returns a empty array.
I just want it to return Newfile and what type of change. Any Ideas?
You can use the following JsonPath to retrieve the commits which list "NEWFILE" as an added file :
$.payload.commits[?(#.changed_files.added.indexOf("NEWFILE") != -1)]

Use of ResultTemplate in vsts extension tasks

I created a task that talks to a REST API to retreive the values for 2 picklists.
Filling the first dropdown box works fine, when using just the jsonpath.
Based on the first picklist I'd like to retreive values of the second list.
I've tried some variations and I'm trying something like this:
The json which I receive in the first rest call is similar to:
{
"id": "45",
"href": "https://selfservice/api/configurations/45/",
"name": "Type",
"description": "",
"version": "0.0.4",
"attributes": [
{
"value": {
"sdk-object": {
"type": "ConfigurationElement",
"id": "56"
}
},
"type": "ConfigurationElement",
"name": "win"
},
{
"value": {
"sdk-object": {
"type": "ConfigurationElement",
"id": "57"
}
},
"type": "ConfigurationElement",
"name": "lin"
}
]
}
I try to show the attributes name in the list and need the id of the attribute in the second picklist.
I created the following datasourcebindings in the task.json. Of course, the targets exist in the task.
task.json:
{
"id": "GUID",
"name": "Spinup",
"friendlyName": "Create environment",
"description": "Starts Workflow to create an environment. ___ The following placeholders are created deplending on the template and can be used in the rest of the release:**XLDEnvironment** and **testAgentHostname**",
"category": "Deploy",
"author": "***",
"version": {
"Major": 0,
"Minor": 0,
"Patch": 33
},
"minimumAgentVersion": "1.95.3",
"inputs": [
{
"label": "Endpoint",
"name": "connectedServiceName",
"required": true,
"type": "connectedService:server",
"helpMarkDown": "endpoint to connect to."
},
{
"name": "stage",
"type": "string",
"label": "Stage",
"defaultValue": "$(Release.EnvironmentName)",
"required": true,
"helpMarkDown": "Stage of the release, default value is based on the pipeline."
},
{
"name": "releaseName",
"type": "string",
"label": "Environment name",
"defaultValue": "$(Release.ReleaseName)",
"required": true,
"helpMarkDown": "Name of the environment that will be created."
},
{
"name": "owner",
"type": "string",
"label": "Owner of the environment",
"defaultValue": "***",
"required": true,
"helpMarkDown": "It is common to use the initials of the product owner in this field. There has to be a valid AD user owner of each environment. This can also be set by using a variable through the pipeline."
},
{
"name": "group",
"type": "string",
"label": "Group of the owner",
"defaultValue": "",
"required": true,
"helpMarkDown": "group that owns the environment. groups can be requested by the infrastructure department. Example: ****"
},
{
"name": "platform",
"type": "pickList",
"label": "Platform (OS)",
"defaultValue": "",
"required": true,
"helpMarkDown": "Choose the type of the target platform."
},
{
"name": "size",
"type": "pickList",
"label": "Environment Template",
"defaultValue": "",
"required": true,
"helpMarkDown": "Size of the environment to create."
}
],
"dataSourceBindings": [
{
"dataSourceName": "GetCEPlatformType",
"endpointId": "$(connectedServiceName)",
"target": "platform",
"selector": "jsonpath:$.attributes[*].name",
"keySelector": "jsonpath:$.attributes[*].value.sdk-object.id"
},
{
"dataSourceName": "GetCEPlatformSize",
"endpointId": "$(connectedServiceName)",
"target": "size",
"parameters": {
"platformTypeId": "$(platform)"
}
}
],
"instanceNameFormat": "Spin up $(size) $(platform) environment",
"execution": {
"PowerShell3": {
"target": "$(currentDirectory)\\task.ps1",
"argumentFormat": "",
"workingDirectory": "$(currentDirectory)"
}
}
}
vss-extension.json:
{
"manifestVersion": 1,
"id": "*****",
"name": "Release Tasks",
"version": "1.0.1",
"publisher": "***",
"targets": [
{
"id": "Microsoft.VisualStudio.Services"
}
],
"description": "Tools to contact ***. Includes a task to spin up a platform and a task to remove the platform.",
"categories": [
"Build and release"
],
"icons": {
"default": "images/extension-icon.png"
},
"files": [
{
"path": "RemoveEnvironment"
},
{
"path": "SpinUpEnvironment"
}
],
"contributions": [
{
"id": "******",
"type": "ms.vss-distributed-task.task",
"targets": [
"ms.vss-distributed-task.tasks"
],
"properties": {
"name": "RemoveEnvironment"
}
},
{
"id": "*********",
"type": "ms.vss-distributed-task.task",
"targets": [
"ms.vss-distributed-task.tasks"
],
"properties": {
"name": "SpinUpEnvironment"
}
},
{
"description": "Service Endpoint type for all connections",
"id": "endpoint-type",
"properties": {
"authenticationSchemes": [
{
"inputDescriptors": [
{
"description": "Username",
"id": "username",
"inputMode": "textbox",
"name": "Username",
"validation": {
"dataType": "string",
"isRequired": true
}
},
{
"description": "Password",
"id": "password",
"inputMode": "passwordbox",
"isConfidential": true,
"name": "Password",
"validation": {
"dataType": "string",
"isRequired": false
}
}
],
"type": "ms.vss-endpoint.endpoint-auth-scheme-basic"
}
],
"dataSources": [
{
"endpointUrl": "api/configurations/*****/",
"name": "GetCEPlatformType",
"resultSelector": "jsonpath:$.attributes[*].name"
},
{
"endpointUrl": "api/configurations/$(platformTypeId)/",
"name": "GetCEPlatformSize",
"resultSelector": "jsonpath:$.attributes[*].name"
}
],
"displayName": "*****",
"helpMarkDown": "Enter the url and credentials to connect to the endpoint.",
"name": "server",
"url": {
"displayName": "Server URL",
"helpText": "Url for the server to connect to."
}
},
"targets": [
"ms.vss-endpoint.endpoint-types"
],
"type": "ms.vss-endpoint.service-endpoint-type"
}
]
}
Sadly I can't get this to work. The datasources exist in the endpoint, but I'm not sure what to do with the resultSelector.
Does anyone have an idea on how to get this to work? The documentation on this isn't too good.
I'm not familiar with mustache, but in the mustache test tool this seems to work.
Thoughts are appreciated!
Try with this in the first data source:
{
"dataSourceName": "dsList1",
"endpointId": "$(connectedServiceName)",
"target": "list1",
"selector": "jsonpath:$.attributes[*].name",
"keySelector": "jsonpath:$.attributes[*].value.sdk-object.id"
}
Update:
You were trying to use "platformTypeId" in vss-extension.json file while it was defined in task.json, this cause the error message you mentioned in the comment.
By the way, I just noticed that you are using "dataSourceBindings", then you cannot use "selector" and "KeySelector" to parse the result since they are used for "sourceDefinitions".
To achieve the feature you want with "dataSourceBindings", you can definition the endpoint url in the task.json directly instead of defining datasource in endpoint contribution.
So you can move the datasources section in the vss-extension.json file first, and then in the task.json file, change to following:
"dataSourceBindings": [
{
"endpointId": "$(connectedServiceName)",
"endpointURL": "api/configurations/*****/",
"target": "platform",
"resultselector": "jsonpath:$.attributes[*]",
"resultTemplate": "{ \"Value\" : \"{{{value.id}}}\", \"DisplayValue\" : \"{{{name}}}\" }"
},
{
"endpointId": "$(connectedServiceName)",
"endpointURL": "api/configurations/$(platformTypeId)/",
"target": "size"
}
],