Parsing facebook signed response json - facebook

I have a app of google app engine for for java and it have a facebook form which on submitting send a signed_request to a servlet in our app. We are using following code to unencrypt and convert to a json string
String signedRequest = (String) req.getParameter("signed_request");
String payload = signedRequest.split("[.]", 2)[1];
payload = payload.replace("-", "+").replace("_", "/").trim();
String jsonString = new String(Base64.decodeBase64(payload.getBytes()));
System.out.println("Json is::" + jsonString);
The response looks like
[sakshumweb/3.361739372881481188].: Json is::{"algorithm":"HMAC-SHA256","expires":1347588000,"issued_at":1347584290,"oauth_token":"XXXXX","registration":{"name":"Vik Kumar","first_name":"Vik","last_name":"Kumar","bloodGroup":"B-","gender":"male","birthday":"10/31/1983","email":"vik.ceo\u0040gmail.com","cellPhone":"1234123456","homePhone":"1234123457","officePhone":"1234123458","primaryAddress":"jdfjfgj","area":"jfdjdfj","location":{"name":"Redwood Shores, California","id":103107903062719},"subscribe":true,"eyePledge":false,"reference":"fgfgfgfg"},
"registration_metadata":{"fields":"[{\"name\":\"name\"},{\"name\":\"first_name\"},{\"name\":\"last_name\"}, {\"name\":\"bloodGroup\", \"description\":\"Blood Group\", \"type\":\"select\", \"options\":{\"A+\":\"A+\",\"A-\":\"A-\",\"B+\":\"B+\",\"B-\":\"B-\",\"O+\":\"O+\",\"O-\":\"O-\",\"AB+\":\"AB+\",\"AB-\":\"AB-\",\"A1+\":\"A1+\",\"A1-\":\"A1-\",\"A2+\":\"A2+\",\"A2-\":\"A2-\",\"A1B+\":\"A1B+\",\"A1B-\":\"A1B-\",\"A2B+\":\"A2B+\",\"A2B-\":\"A2B-\",\"HH\":\"Bombay Blood Group\"}}, {\"name\":\"gender\"}, {\"name\":\"birthday\"},{\"name\":\"email\"}, {\"name\":\"cellPhone\", \"description\":\"Cell Number\", \"type\":\"text\"}, {\"name\":\"homePhone\", \"description\":\"Home Number\", \"type\":\"text\"}, {\"name\":\"officePhone\", \"description\":\"Office Number\", \"type\":\"text\"}, {\"name\":\"primaryAddress\", \"description\":\"Primary Address\", \"type\":\"text\"}, {\"name\":\"area\", \"description\":\"Locality/Village/Area\", \"type\":\"text\"},{\"name\":\"location\"}, {\"name\":\"subscribe\", \"description\":\"Subscribe me for the Sakshum activites updates.\", \"type\":\"checkbox\", \"default\":\"checked\"}, {\"name\":\"eyePledge\", \"description\":\"I want to pledge my eyes as well.\", \"type\":\"checkbox\"}, {\"name\":\"reference\", \"description\":\"How you reached to us (Friend, Facebook, google etc.)?\", \"type\":\"text\"}]"},"user":{"country":"us","locale":"en_GB"},"user_id":"875390603"}
So, how do i parse this data to extract the data in registration part of this response?

Since this is a valid JSON, you can use JSON library like Jackson or GSON to parse it.
You can use this example code to print out all registration fields:
JsonNode json = new ObjectMapper().readTree(response);
JsonNode registration_fields = json.get("registration");
Iterator<String> fieldNames = registration_fields.getFieldNames();
while(fieldNames.hasNext()){
String fieldName = fieldNames.next();
String fieldValue = registration_fields.get(fieldName).asText();
System.out.println(fieldName+" : "+fieldValue);
}

Related

How to parse JSON data and print on terminal in flutter?

This is my Json data :
{
"result":"0",
"school_name":"Global Academy International",
"school_code":"GAIS",
"dashboard":"{\"privilege\":[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":159,\"privilege_desc\":\"V4_MYATTENDANCE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1188},{\"activity_id\":159,\"privilege_desc\":\"V4_MYLEAVESTATUS\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1189},{\"activity_id\":159,\"privilege_desc\":\"V4_MEMO\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1193},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1198},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISELATE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1201},{\"activity_id\":162,\"privilege_desc\":\"V4_LEAVE_REQUISITION\",\"activity_desc\":\"V4_TEACHER_LEAVE\",\"privilege_id\":1203},{\"activity_id\":164,\"privilege_desc\":\"V4_ASSIGNMENT\",\"activity_desc\":\"V4_STUDENT_ASSIGNMENT\",\"privilege_id\":1206},{\"activity_id\":166,\"privilege_desc\":\"V4_SCHOOL_CALENDAR\",\"activity_desc\":\"V4_CALENDAR\",\"privilege_id\":1208},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}],\"resultPrivilege\":\"0\",\"resultProfile\":\"0\",\"profile\":{\"empid\":\"EMP183\",\"name\":\"BACHIR Raji Kashkash\",\"designation\":\"TEACHER\",\"photo_path\":\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\",\"department_name\":\"HIGH SCHOOL - T\"}}",
"employee_id":"EMP183",
"school_url":"http://ict.gaiqatar.com"
}
I want to print only this data from jSON data:
[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}]
How to get this data from whole jSON data ?
Import the following package:
import 'dart:convert';
Decode the json result returned and access the specific field you want:
final body = json.decode(response.dashboard);
print(body['privilege']);
Basically after parsing your initial json you need to parse the nested field as well (privileges) since it's not a valid json object. Usually I would do this from the server and send a proper json response to the client (flutter).
If this can't be done then you just have to parse the json response, walk through it and parse and nested fields as well.
Edit:
Noticed your json wasn't formatted properly this is an example code. You can run this in dartpad
import 'dart:convert';
void main() {
final jsonString = '{\"privilege\":[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}],\"resultPrivilege\":\"0\",\"resultProfile\":\"0\"}';
final parsedJson = json.decode(jsonString);
final privilege = parsedJson['privilege'];
print(privilege);
}
The problem is your json is not properly formatted. first format it properly, you can copy and paste your json in any prettify json website and try to format it properly, if problem persists then do let me know.
The Json Data
final jsonData = """{
"result":"0",
"school_name":"Global Academy International",
"school_code":"GAIS",
"dashboard":"{\\"privilege\\":[{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYPROFILE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1185},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYTIMETABLE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1186},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYATTENDANCE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1188},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYLEAVESTATUS\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1189},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MEMO\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1193},{\\"activity_id\\":161,\\"privilege_desc\\":\\"V4_SUBJECTWISE\\",\\"activity_desc\\":\\"V4_STUDENT_ATTENDANCE\\",\\"privilege_id\\":1198},{\\"activity_id\\":161,\\"privilege_desc\\":\\"V4_SUBJECTWISELATE\\",\\"activity_desc\\":\\"V4_STUDENT_ATTENDANCE\\",\\"privilege_id\\":1201},{\\"activity_id\\":162,\\"privilege_desc\\":\\"V4_LEAVE_REQUISITION\\",\\"activity_desc\\":\\"V4_TEACHER_LEAVE\\",\\"privilege_id\\":1203},{\\"activity_id\\":164,\\"privilege_desc\\":\\"V4_ASSIGNMENT\\",\\"activity_desc\\":\\"V4_STUDENT_ASSIGNMENT\\",\\"privilege_id\\":1206},{\\"activity_id\\":166,\\"privilege_desc\\":\\"V4_SCHOOL_CALENDAR\\",\\"activity_desc\\":\\"V4_CALENDAR\\",\\"privilege_id\\":1208},{\\"activity_id\\":168,\\"privilege_desc\\":\\"V4_LOGOUT\\",\\"activity_desc\\":\\"V4_LOGOUT\\",\\"privilege_id\\":1210}],\\"resultPrivilege\\":\\"0\\",\\"resultProfile\\":\\"0\\",\\"profile\\":{\\"empid\\":\\"EMP183\\",\\"name\\":\\"BACHIR Raji Kashkash\\",\\"designation\\":\\"TEACHER\\",\\"photo_path\\":\\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\\",\\"department_name\\":\\"HIGH SCHOOL - T\\"}}",
"employee_id":"EMP183",
"school_url":"http://ict.gaiqatar.com"
}""";
Used double \\ to scape correctly the char "...
And then:
final parsedJson = json.decode(jsonData);
print(parsedJson['dashboard']);
If you prefer, you can parse only dashboard section to filter some itens programaticaly...
final dashboardParsed = json.decode(parsedJson['dashboard']);
print(dashboardParsed);
Final result
final jsonData = """{
"result":"0",
"school_name":"Global Academy International",
"school_code":"GAIS",
"dashboard":"{\\"privilege\\":[{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYPROFILE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1185},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYTIMETABLE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1186},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYATTENDANCE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1188},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYLEAVESTATUS\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1189},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MEMO\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1193},{\\"activity_id\\":161,\\"privilege_desc\\":\\"V4_SUBJECTWISE\\",\\"activity_desc\\":\\"V4_STUDENT_ATTENDANCE\\",\\"privilege_id\\":1198},{\\"activity_id\\":161,\\"privilege_desc\\":\\"V4_SUBJECTWISELATE\\",\\"activity_desc\\":\\"V4_STUDENT_ATTENDANCE\\",\\"privilege_id\\":1201},{\\"activity_id\\":162,\\"privilege_desc\\":\\"V4_LEAVE_REQUISITION\\",\\"activity_desc\\":\\"V4_TEACHER_LEAVE\\",\\"privilege_id\\":1203},{\\"activity_id\\":164,\\"privilege_desc\\":\\"V4_ASSIGNMENT\\",\\"activity_desc\\":\\"V4_STUDENT_ASSIGNMENT\\",\\"privilege_id\\":1206},{\\"activity_id\\":166,\\"privilege_desc\\":\\"V4_SCHOOL_CALENDAR\\",\\"activity_desc\\":\\"V4_CALENDAR\\",\\"privilege_id\\":1208},{\\"activity_id\\":168,\\"privilege_desc\\":\\"V4_LOGOUT\\",\\"activity_desc\\":\\"V4_LOGOUT\\",\\"privilege_id\\":1210}],\\"resultPrivilege\\":\\"0\\",\\"resultProfile\\":\\"0\\",\\"profile\\":{\\"empid\\":\\"EMP183\\",\\"name\\":\\"BACHIR Raji Kashkash\\",\\"designation\\":\\"TEACHER\\",\\"photo_path\\":\\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\\",\\"department_name\\":\\"HIGH SCHOOL - T\\"}}",
"employee_id":"EMP183",
"school_url":"http://ict.gaiqatar.com"
}""";
final parsedJson = json.decode(jsonData);
print(parsedJson['dashboard']);
final dashboardParsed = json.decode(parsedJson['dashboard']);
print(dashboardParsed);
I Scaped \" because I'm storing the string into a var, if it comes from your web api, should work too.

How to send a very long xml file as payload in rest API Automation

I want to sent a very long xml as a payload in rest API Automation.
I am using the HTTP client framework.
restClient = new RestClient();
HashMap < String, String > headerMap = new HashMap < String, String > ();
headerMap.put("Content-Type", "application/xml");
headerMap.put("Ocp-Apim-Subscription-Key", "7531bf090b6b49199ec37f9c818dc417");
//jackson API:
ObjectMapper mapper = new ObjectMapper();
Users users = new Users("morpheus", "leader"); //expected users obejct
//object to json file:
You can create object of your XML and set the data using the getter functions() or create a xml file and put it into your project with some pupolated data which will always remain common. Read the external xml file and change it depending on your requirements before making request.
Everything in body can be send as String, save long complex xml to in a file & then convert your XML file to string and pass to that json variable.
JsonRequest{
"name" : "${name}"
}
name= FileUtil.readFileToString(new File(file), StandardCharsets.UTF_8);

eBay REST API Get Offers Authetication Error

I am attempting to get eBay product IDs using the GetOffers request by sending it a product SKU.
My code is below, the problem I am currently having is that when I try to test this code is returns a 401 unauthorized. It's not returning any specific error code or anything descriptive.
I know my access token is valid I can't find any good examples on how to use this request.
public string getEbayOffers(string sku)
{
HttpResponseMessage response;
string accessToken = "tokenhere";
string param = Convert.ToBase64String(Encoding.ASCII.GetBytes(accessToken));
string url = $"sell/inventory/v1/offer?sku={sku}";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.ebay.com/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", param);
response = client.GetAsync(url).Result;
}
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsStringAsync().Result;
}
return null;
}
No need to convert your token to base64. The correct format should be "Bearer YOUR_USER_TOKEN". Replace YOUR_USER_TOKEN with your own token string.
Access token should be enough for getting offers but maybe you can try to use user token if above doesn't work.

Facebook SDK C#

I am trying to parse the facebook api via someid/feed api using Facebook SDK C#. But I cannot parse the keys quite right. Does anyone have an example of how this should work?
dynamic fb = new FaceBookClient(token);
dynamic feed = fb.Get("123456/feed");
var msg = feed.message; // (do not get intellisense)
or
var msg = feed["message]; //(returns No data key found error.)
You need to pass also appId and appSecret to FaceBookClient.
So instead of picking up a constructor, do the settings in Web.Config:
<facebookSettings appId="123" appSecret="abc" siteUrl="..." canvasPage="..." canvasUrl=".." cancelUrlPath="..." />
then try:
FacebookWebClient fbWebClient = new FacebookWebClient();
dynamic result = fbWebClient.Get("123456/feed");
Feed returns a JSON Array wrapped in a result object. Get the result object by calling feed.First(), then loop through the JsonArray to get the individual posts.
const string url = "/me/feed";
IDictionary<string, object> feed = FacebookClient.Get(url, parameters);
JsonArray posts = feed.First().Value as dynamic;
return posts;
It is so simple as I see.
public dynamic GetFeeds()
{
dynamic feeds = facebookClientProvider.CreateOne().Get("/me/feed");
//feeds.data
//feeds.paging
return feeds;
}
The feeds.data will contain the feeds and the data.paging will contain a url where you can download the following feeds.
I'm using Facebook C#SDK Runtime version:v4.0.30319 and Version:6.0.10.0

Using Facebook Requests 2.0 with the C# SDK

I am trying to update the bookmark count field with the SDK but have not had any success yet.
Can somebody tell me what classes I need to instantiate to do something similar to the following link:
http://developers.facebook.com/blog/post/464
Note:
The link demonstrates how to set the bookmark count and delete it. I would like to be able to do the same with the SDK, any help would be appreciated.
To do this, first you need to get you app's access token:
private string GetAppAccessToken() {
var fbSettings = FacebookWebContext.Current.Settings;
var accessTokenUrl = String.Format("{0}oauth/access_token?client_id={1}&client_secret={2}&grant_type=client_credentials",
"https://graph.facebook.com/", fbSettings.AppId, fbSettings.AppSecret);
// the response is in the form: access_token=foo
var accessTokenKeyValue = HttpHelpers.HttpGetRequest(accessTokenUrl);
return accessTokenKeyValue.Split('=')[1];
}
A couple of things to note about the method above:
I'm using the .Net HttpWebRequest instead of the Facebook C# SDK to grab the app access_token because (as of version 5.011 RC1) the SDK throws a SerializationException. It seems that the SDK is expecting a JSON response from Facebook, but Facebook returns the access token in the form: access_token=some_value (which is not valid JSON).
HttpHelpers.HttpGetRequest simply uses .Net's HttpWebRequest. You can just as well use WebClient, but whatever you choose, you ultimately want to make this http request:
GET https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials HTTP/1.1
Host: graph.facebook.com
Now that you have a method to retrieve the app access_token, you can generate an app request as follows (here I use the Facebook C# SDK):
public string GenerateAppRequest(string fbUserId) {
var appAccessToken = GetAppAccessToken();
var client = new FacebookClient(appAccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = "Test: Action is required";
parameters.data = "Custom Data Here";
string id = client.Post(String.Format("{0}/apprequests", fbUserId), parameters);
return id;
}
Similarly, you can retrieve all of a user's app requests as follows:
Note: you probably don't want to return "dynamic", but I used it here for simplicity.
public dynamic GetAppRequests(string fbUserId) {
var appAccessToken = GetAppAccessToken();
var client = new FacebookClient(appAccessToken);
dynamic result = client.Get(String.Format("{0}/apprequests", fbUserId));
return result;
}
I hope this helps.