parse the contents of JSON data - flutter

I have an error in prase JSON data API flutter,
the is the response from API
{
"response": {
"message": "Loaction Found",
"responseCode": 0
},
"Loaction": {
"driver_id": 1,
"Latitude": "31.959727",
"longitude": "35.837615",
"time": "12/04/2020 16:09:33"
}
}
I made the model from the https://javiercbk.github.io/json_to_dart/
but I can't know how to prase the contents of JSON data, I try using the below code, but I didn't receive and data,
can anyone help me ??
this is my all code:
https://github.com/mohmmed750/flutter-json/blob/master/json-flutter

Please remove this code
for (Map i in jsonData) {
_list.add(DriverLocation.fromJson(i));
}
And use this code instead
_list.add(DriverLocation.fromJson(jsonData));
Then you can print in the console using, to see the list items.
for (var i = 0; i < _list.length; i++) {
DriverLocation dl = _list[i];
print(dl.loaction.driverId);
}

You don't need to parse the json with DriverLocation class. You can straight off get the Loaction key from jsonData and parse it with Loaction.fromJson() directly.
Something like this:
var location = jsonData['Loaction'];
_list.add(Loaction.fromJson(location));
Code that I tried out - https://dartpad.dev/63fdc82ea0f6641698d42fcde47811f2
Hope this helps!

Related

Finding Descriptor Identifier using devops REST API

I am trying to make a post to the dev.azure.com{organization}/_apis/accesscontrolentries/{namespaceId}?api-version=5.1.
I need help on obtaining the descriptor that starts with S-1-9.
{ "token": "", "merge": true, "accessControlEntries": [ { "descriptor": "Microsoft.TeamFoundation.Identity;S-1-9-**********-**********-**********-**********-**********-*-**********-**********-**********-**********", "allow": 128, "deny": 0 } ] }
Thank you.
Obtaining the descriptor that starts with S-1-9.
There’s no directly rest api to get this descriptor which start with S-1-9. You need to use the follow api get the user descriptor(SID) firstly:
GET https://vssps.dev.azure.com/{org name}/_apis/graph/users?api-version=5.1-preview.1
I have one answer about how to obtain it from response body, please refer to this answer for more details.
Now the descriptor we get is based on base64. To achieve what you want, just decode this SID.
Here has a blog which written by our Azure Identity Team engineer: C# Decode script. Just located to the corresponding part to achieve this decode script:
public static string Base64Decode(string base64EncodedData)
{
var lengthMod4 = base64EncodedData.Length % 4;
if (lengthMod4 != 0)
{
//fix Invalid length for a Base-64 char array or string
base64EncodedData += new string('=', 4 - lengthMod4);
}
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}

Is there a way to access API response data before the response has completed?

Some APIs don't have pagination implemented. Is there a way to access the partial response and access available objects before the API call has completed? For example if the response is json and the data that has already been received is:
{"objectarray": [
{"Name": "test1"},
{"Name": "test2"},
{"Name":
The first 2 elements are already loaded and can parsed. Why wait for the whole response to complete?
I guess there some problems with this approach. Please share thoughts.
I've written a code sample that does what I need. Is there a better way to do it? Please share thoughts.
WebClient client = new WebClient();
Stream str = client.OpenRead(<url>);
using (JsonTextReader reader = new JsonTextReader(new StreamReader(str)))
{
while (reader.Read())
{
if (reader.TokenType == JsonToken.StartArray)
{
while (reader.Read())
{
if (reader.TokenType == JsonToken.StartObject)
{
var jsonObject = JObject.Load(reader);
var deserialized = jsonObject.ToObject<T>();
}
}
}
}
}

Elastic search - Unable to filter the JSON exact body using RestClient

Trying to query the exact JSON body by using Elastic search with RestClient API, but getting the whole body as response with hits,_source,etc.
So tried the filter_path [[filter_path=hits.hits._source]] approach in order to resolve this, but even that won't help to fetch exact body and coming with _source tag as mentioned below filter_path Response.
Can any one suggest please howt to get the exact json body as response like
{ "testAcct":"1234" }
Client.java:-
RestClient client = RestClient.builder(
new HttpHost(HOST, 9200, HTTP)).build();
Response response1 = client.performRequest("GET", SERVICE_URL + "_search",
Collections.<String, String>emptyMap(), new BasicHeader("testAcct", "1234"));
System.out.println(EntityUtils.toString(response1.getEntity()));
Response:-
{
"took":6,
"timed_out":false,
"_shards":{
"total":1,
"successful":1,
"failed":0
},
"hits":{
"total":21,
"max_score":1.0,
"hits":[
{
"_index":"testindex",
"_type":"testexternal",
"_id":"AVmHwA7Pkw5MudRUOp-q",
"_score":1.0,
"_source":{
"testAcct":"1234"
}
}
}
]
}
filter_path Response:-
{
"hits":{
"hits":[
{
"_source":{
"testAcct":"1234"
}
}
}
}

Need one help regarding fetching data value from response

Need one help regarding fetching data value from response.
Below is my response which I got after hitting URL.
{
"response": {
"Error Message": "Invalid Input missing",
"success": "false""
}
}
In this I want to read "Error Message" through POSTMAN test. For same reason I have written below code, but it is not working due to space between key.
var data = JSON.parse(responseBody);
tests ["Verify Error message"] = data.response.Error Message==="Invalid Input - Mandatory data(Company ID/source Id/SalesRep Ids/ContactPerson Ids) missing";
You're trying to use Error Message as a field with a space in it. Try:
tests ["Verify Error message"] = data.response.["Error Message"]==="Invalid Input - Mandatory data(Company ID/source Id/SalesRep Ids/ContactPerson Ids) missing";
This is not good to compare string.
In your response you must have like this,
{
"response": {
"Error Message": "Invalid Input missing",
"success": "false",
"responseCode" : 400
}
}
for more response codes, please go to this link,
http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
Then after do comparison,
var data = JSON.parse(responseBody);
if(data.reponse.responseCode == '400'){
// do stuff
}

How to receive an image in a Facebook Messenger bot

How can I receive an attachment in form of an image through the Facebook Messenger API?
Their documentation only provides instructions on how to receive text-based messages.
I am not sure what language you are using to code your bot but since you are referring to the facebook documents where most of the messenger code snippets are in node.js
Here's something for you to try, let me know if this helps.
app.post('/webhook/', function (req, res) {
//Getting the mesagess
var messaging_events = req.body.entry[0].messaging;
//Looping through all the messaging events
for (var i = 0; i < messaging_events.length; i++) {
var event = req.body.entry[0].messaging[i];
//Checking for attachments
if (event.message.attachments) {
//Checking if there are any image attachments
if(atts[0].type === "image"){
var imageURL = atts[0].payload.url;
console.log(imageURL);
}
}
}
}
In February 2017 I came across the same issue and struggled to get this up and running for a very long time. Turns out that the message.attachments comes in as object, where the actual attachment is within the object.
The structure goes like this:
Attachments Object > JSON Response >Type & Payload > URL
app.post('/webhook/', function(req, res) {
let messaging_events = req.body.entry[0].messaging
for (let i = 0; i < messaging_events.length; i++) {
let event = req.body.entry[0].messaging[i]
let sender = event.sender.id
// Check if it's a message
if (event.message) {
//Create the attachment
let attachment = event.message.attachments
// Here we access the JSON as object
let object1 = attachment[0];
//Here we access the payload property
let payload = object1.payload;
// Finally we access the URL
let url = payload.url;
console.log(url)
}
else if (event.message && event.message.text) {
// Here you can handle the text
console.log("Just Text")
}
}
res.sendStatus(200)
})
The more compact version without explanations looks like this:
if (event.message) {
let attachment = event.message.attachments
console.log(attachment[0].payload.url)
}
As added bonus, you could also check if the type is an Image. You can achieve that by adding doing this adjustment:
if (event.message && ) {
let attachment = event.message.attachments[0]
if (attachment.type === "image") {
console.log(attachment.payload.url)
}
}
Hope this helps,
Julian
While in PYTHON to receive and save an image attachment in your facebook chatbot works:
#app.route('/', methods=['POST'])
def webhook(): # endpoint for processing incoming messaging events
data = request.get_json()
if data["object"] == "page":
for entry in data["entry"]:
for messaging_event in entry["messaging"]:
if messaging_event["message"].get("attachments"):
attachment_link = messaging_event["message"]["attachments"][0]["payload"]["url"]
print("Image received, boss!")
print(attachment_link)
good chatbot-thing!
Marco
In PHP,
When user sents it to bot, below response we get which contains attachement type and url
{
"object": "page",
"entry": [
{
"id": "000000000000000",
"time": 1511956708068,
"messaging": [
{
"sender": {
"id": "000000000000000"
},
"recipient": {
"id": "000000000000000"
},
"timestamp": 1511956707862,
"message": {
"mid": "mid.$xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"seq": 42172,
"sticker_id": 369239263222822,
"attachments": [
{
"type": "image",
"payload": {
"url": "https:\/\/scontent.xx.fbcdn.net\/v\/t39.1997-6\/851557_369239266556155_759568595_n.png?_nc_ad=z-m&_nc_cid=0&oh=9058fb52f628d0a6ab92f85ea310db0a&oe=5A9DAADC",
"sticker_id": 369239263222822
}
}
]
}
}
]
}
]
}
This is how you get different type of messages from user
//get the response from user
$input = json_decode(file_get_contents('php://input'), true);
//first check if attachment is present
$attachment = array_key_exists('attachments', $input['entry'][0]['messaging'][0]['message']);
//get the attachement type and url
$type = $input['entry'][0]['messaging'][0]['message']['attachments'][0]['type'];
$file_url = $input['entry'][0]['messaging'][0]['message']['attachments'][0]['payload']['url'];
Hope this helps you
https://developers.facebook.com/docs/messenger-platform/implementation#receive_message
Check this link out.
It says that,
"Messages may have an image, video or audio attachment."
UPDATE:
The above link is broken as Facebook recently updated their documentations in a weirdly downgraded version with many contents missing.
To elaborate as pointed out in the comment, when a user sends a request, your server will receive such a json:
{
"mid": "some mid",
"seq": 26,
"attachments": [{
"type": "image",
"payload": {
"url": "some image url"
}
}]
}
and you can maybe create a download function to download the image to your server.
To use this data, as mentioned above, you can use the webhook.
app.post('/webhook', function (req, res) {
var data = req.body;
// Make sure this is a page subscription
if (data.object == 'page') {
console.log(data.entry);
// Iterate over each entry
// There may be multiple if batched
data.entry.forEach(function(pageEntry) {
var pageID = pageEntry.id;
var timeOfEvent = pageEntry.time;
// Iterate over each messaging event
pageEntry.messaging.forEach(function(messagingEvent) {
receivedMessage(messagingEvent);
});
});
// Assume all went well.
//
// You must send back a 200, within 20 seconds, to let us know you've
// successfully received the callback. Otherwise, the request will time out.
res.sendStatus(200);
}
});
function receivedMessage(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;
if (senderID == PAGE_ID) {
console.error("Sender is self.");
return;
}
console.log("Received message for user %d and page %d at %d with message:",
senderID, recipientID, timeOfMessage);
console.log(JSON.stringify(message));
var messageId = message.mid;
// You may get a text or attachment but not both
var messageText = message.text;
var messageAttachments = message.attachments;
if (messageText) {
// If we receive a text message, check to see if it matches any special
// keywords and send back the corresponding example. Otherwise, just echo
// the text we received.
} else if (messageAttachments) {
messageAttachments.forEach(function(messageAttachment) {
var attachmentUrl = messageAttachment.payload.url;
console.log("Received Attachment");
download(attachmentUrl);
}
}
This code was taken from the sample code of Facebook.