How to send 'JSON' in post request using deluge? - json

I have a JSON data, which i need to pass it in POST method. I have no idea how to convert JSON data as query paramters. Kindly help me how to send this type of a JSON data in POST method using deluge.
jsonData = {
"author": "urn:li:person:12345",
"lifecycleState": "PUBLISHED",
"specificContent": {
"com.linkedin.ugc.ShareContent": {
"shareCommentary": {
"text": "Hello World! This is my first Share on LinkedIn!"
},
"shareMediaCategory": "NONE"
}
},
"visibility": {
"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
}
}
This is what i actually tried:
headerData = Map();
headerData.put("Content-Type","application/json charset=utf-8");
headerData.put("X-Restli-Protocol-Version","2.0.0");
headerData.put("x-li-format","json");
//json data
fields = "{\"author\":\"urn:li:person:368964147\",\"lifecycleState\":\"PUBLISHED\",\"specificContent\": {\"com.linkedin.ugc.ShareContent\":{\"shareCommentary\":{\"text\": \"Hello World! This is my first Share on LinkedIn!\"},\"shareMediaCategory\": \"NONE\"}},\"visibility\":{\"com.linkedin.ugc.MemberNetworkVisibility\":\"PUBLIC\"}}";
//info fields;
response = invokeurl
[
url :"https://api.linkedin.com/v2/ugcPosts"
type :POST
parameters:fields
headers:headerData
connection:"li"
];
info response;
I expect:
params = Map();
params.put("author","urn:li:person:12345");
params.put("lifecycleState","PUBLISHED");
...so on
Thanks.

I found the deluge code to convert JSON data to query parameters.
param = Map();
param.put("author","urn:li:person:YoTjU8Fmfk");
param.put("lifecycleState","PUBLISHED");
specificContent = Map();
ShareContent = Map();
shareCommentary = Map();
shareCommentary.put("text","Hello World! This is my first Share on LinkedIn!");
ShareContent.put("shareCommentary",shareCommentary);
specificContent.put("com.linkedin.ugc.ShareContent",ShareContent);
specificContent.put("shareMediaCategory","NONE");
param.put("specificContent",specificContent);
visibility = Map();
visibility.put("com.linkedin.ugc.MemberNetworkVisibility","PUBLIC");
param.put("visibility",visibility);

Related

Unhandled Exception: type 'String' is not a subtype of type 'List<dynamic>'

I'm trying to parse the images from images from the json response, but I'm getting as error stating as Unhandled Exception: type 'String' is not a subtype of type 'List'
{
"status": true,
"record": {
"adid": "3",
"adsubcatid": "7",
"aduserid": "2",
"adname": "wfw fw",
"adcoverimg": "http://codecell.in/girrivi/assets/adcover/ic_service_search.png",
"addesc": "e fe fe ",
"ads_price": "5000",
"ads_location": "mysuru",
"created_date": "13/10/2020",
"user_name": "sunil",
"images": "{'adsimg_img':'http://codecell.in/girrivi/assets/adimgs/carpenter.png'},{'adsimg_img':'http://codecell.in/girrivi/assets/adimgs/electrician.png'},{'adsimg_img':'http://codecell.in/girrivi/assets/adimgs/gardner.png'}"
}
}
List images;
Future<String> getProductDetails() async {
String productDetailsUrl = Constant.productDetailsUrl+widget.id;
print(productDetailsUrl);
Map<String, String> headers = {'Content-Type' : 'application/json'};
final response = await http.get(productDetailsUrl, headers: headers);
print(response.body);
if(response.statusCode == 200){
jsonResponse = json.decode(response.body);
print('Response in Profile Screen: ' + response.body);
print("Price - "+jsonResponse['record']['ads_price']);
setState(() {
price = jsonResponse['record']['ads_price'];
title = jsonResponse['record']['adname'];
description = jsonResponse['record']['addesc'];
location = jsonResponse['record']['ads_location'];
publishedOn = jsonResponse['record']['created_date'];
postedBy = jsonResponse['record']['user_name'];
adId = jsonResponse['record']['adid'];
postedById = jsonResponse['record']['aduserid'];
images = jsonResponse['record']['images'];
});
}
}
I am getting all the details in the right way except the images
As I see in your images response you have this {'adsimg_img': 'some_url'}.
So I would do like this in your code
setState(() {
.
.
.
adId = jsonResponse['record']['adid'];
postedById = jsonResponse['record']['aduserid'];
images = (jsonResponse['record']['images'] as List)
?.map((i) => i['adsimg_img'])
?.toList();
});
So images at the end will look like ['url1', 'url2', ...] // List of Strings
I didn't tested it but it should do the trick :)
In the json response snippet that you have added, the value of images should be an array, but it is in double quotes which is a basically string.
If you put that snippet into a jsonValidator like this one, it shows that the value of the key images is a string, rather than the array that you are expecting.
An array of objects in json is formatted like in this one
{
"user_name": "sunil",
"images": [
{
"adsimg_img":"http://codecell.in/girrivi/assets/adimgs/carpenter.png"
},
{
"adsimg_img":"http://codecell.in/girrivi/assets/adimgs/carpenter.png"
},
{
"adsimg_img":"http://codecell.in/girrivi/assets/adimgs/carpenter.png"
}
]
}

Remove a specific JSONObject from JSONArray in groovy

Say I have a JSON request payload like
{
"workflow": {
"approvalStore": {
"sessionInfo": {
"user": "baduser"
},
"guardType": "Transaction"
}
}
}
I get the value of user via
def user = req.get("workflow").get("approvalStore").get("sessionInfo").get("user")
Now, I get a RestResponse approvalList which I store as list and return to caller as return approvalList.json as JSON. All well so far.
Suppose the response (approvalList.json) looks like below JSONArray -
[
{
"objId": "abc2",
"maker": "baduser"
},
{
"objId": "abc1",
"maker": "baduser"
},
{
"objId": "abc4",
"maker": "gooduser"
}
]
Question : How may I filter the approvalList.json so that it doesn't contain entries (objects) that have "maker": "baduser" ? The value passed to maker should essentially be the user variable I got earlier.
Ideal required output -
It's not entirely clear if you always want a single object returned or a list of objects but using collect is going to be the key here:
// given this list
List approvalList = [
[objId: "abc2", maker: "baduser"],
[objId: "abc1", maker: "baduser"],
[objId: "abc4", maker: "gooduser"]
]
// you mentioned you wanted to match a specific user
String user = "baduser"
List filteredList = approvalList.findAll{ it.maker != user}​​​​​​
// wasn't sure if you wanted a single object or a list...
if (filteredList.size() == 1) {
return filteredList[0] as JSON
} else {
return filteredList as JSON
}​
Pretty simple. First parse the JSON into an object, then walk through and test.
JSONObject json = JSON.parse(text)
json.each(){ it ->
it.each(){ k,v ->
if(v=='baduser'){
// throw exception or something
}
}
}

Parse JSON using groovy script (using JsonSlurper)

I am just two days old to groovy, I need to parse a json file with below structure. My actual idea is I need to run a set of jobs in different environments based on different sequences, so I came up with this format of json as a input file to my groovy
{
"services": [{
"UI-Service": [{
"file-location": "/in/my/server/location",
"script-names": "daily-batch,weekly-batch,bi-weekly-batch",
"seq1": "daily-batch,weekly-batch",
"seq2": "daily-batch,weekly-batch,bi-weekly-batch",
"DEST-ENVT_seq1": ["DEV1", "DEV2", "QA1", "QA2"],
"DEST-ENVT_seq2": ["DEV3", "DEV4", "QA3", "QA4"]
}]
}, {
"Mobile-Service": [{
"file-location": "/in/my/server/location",
"script-names": "daily-batch,weekly-batch,bi-weekly-batch",
"seq1": "daily-batch,weekly-batch",
"seq2": "daily-batch,weekly-batch,bi-weekly-batch",
"DEST-ENVT_seq1": ["DEV1", "DEV2", "QA1", "QA2"],
"DEST-ENVT_seq2": ["DEV3", "DEV4", "QA3", "QA4"]
}]
}]
}
I tried below script for parsing the json
def jsonSlurper = new JsonSlurper()
//def reader = new BufferedReader(new InputStreamReader(new FileInputStream("in/my/location/config.json"),"UTF-8"))
//def data = jsonSlurper.parse(reader)
File file = new File("in/my/location/config.json")
def data = jsonSlurper.parse(file)
try{
Map jsonResult = (Map) data;
Map compService = (Map) jsonResult.get("services");
String name = (String) compService.get("UI-Service");
assert name.equals("file-location");
}catch (E){
println Exception
}
I need to first read all the services (UI-service, Mobile-Service, etc..) then their elements and their value
Or you could do something like:
new JsonSlurper().parseText(jsonTxt).services*.each { serviceName, elements ->
println serviceName
elements*.each { name, value ->
println " $name = $value"
}
}
But it depends what you want (and you don't really explain in the question)
Example for reading from JsonParser object:
def data = jsonSlurper.parse(file)
data.services.each{
def serviceName = it.keySet()
println "**** key:${serviceName} ******"
it.each{ k, v ->
println "element name: ${k}, element value: ${v}"
}
}
other options:
println data.services[0].get("UI-Service")["file-location"]
println data.services[1].get("Mobile-Service").seq1

How can i list the values of a Node in JSON ?

Say, I have a JSON that has an array of "Topics"
I need to list all "created_at" values of all the topics
without the other data , using the Chrome console
P.S : I'm Using JSONView
You can loop through the objects in your array and simply access the property created_at.
Example
var json = {
all_topics: [{
"created_at:" "2016-08-08T10:22:03.123Z",
"name": "topic1"
}, {
"created_at": "2016-08-08T11:43:06.963Z",
"name": "topic2"
}]
}
for (var topic of json.all_topics) {
console.log(topic.created_at);
}
You can use JSON.stringify to turn a JavaScript object into a JSON String, and JSON.parse to turn a JSON string into a JavaScript object.
var jsonString = JSON.stringify(json);
==> {"all_topics":[{"created_at":"2016-08-08T10:22:03.123Z","name":"topic1"},{"created_at":"2016-08-08T11:43:06.963Z","name":"topic2"}]}
var jsonObj = JSON.parse(jsonString);
==> Object {all_topics: Array[2]}
Alternatively, you could return a new array with the filtered property using Array.prototype.map:
var topics = json.all_topics.map(function(obj){
return obj.created_at;
});
==> ["2016-08-08T10:22:03.123Z", "2016-08-08T11:43:06.963Z"]

Pass JSON String into Jstree

I'm, Having trouble passing JSON data into the Jstree.
Following is my Jstree
$("#tree")
.bind("open_node.jstree", function (event, data) {
console.log(data.rslt.obj.attr("id"));
})
.jstree({
"plugins" : ["themes", "json_data", "ui"],
"json_data" : {
"data": [{"data":'Top Level - ',"state":'closed',"attr":{"seq_no":341386}}],
"state" : "open",
"ajax": {
"type": 'POST',
"dataType": 'json',
"data": {"action": 'getChildren'},
"url": function (node) {
var nodeId = node.attr('seq_no');
return 'ajax/test.jsp?seq_no=' + 341386;
},
"success": function (new_data) {
return new_data;
}
}
}
});
And test.jsp looks like this:
RecordCollection result=null;
PlsqlSelectCommand selCmd = null;
String sErrorMsg = "";
String sqlSelect;
OutputFormat format = new OutputFormat( doc ); //Serialize DOM
StringWriter xmlOut = new StringWriter(); //Writer will be a String
XMLSerializer serial = new XMLSerializer( xmlOut, format );
serial.serialize(doc);
JSONObject jsonObject = XML.toJSONObject(xmlOut.toString());
<%=jsonObject%>
The problem is JSON data isnt passed into the jstree. thus I cant set my children nodes. I've tried so hard but can't get this working.
Is there something else I need to do in order to pass this JSON string into the jstree.
My jstree works when the data feed is hard-coded.
Any help is much appreciated.