I have a Facebook reply as follows:
dynamic response = client.Get("me", new { fields = "verified, picture" });
BELOW IS THE JSON IN 'response'
{"verified":true,
"picture":{"data":{"url":"https://www.abc.com","is_silhouette":true}}}
How do I access the 'url' value in the subkey of 'picture'? Here's what I tried but it fails:
fbPicture = response["picture.data.url"].toString();
I've tried different syntax but to no avail and I've also looked around but to no avail.
Thanks in advance !
The Facebook C# SDK implements an object called JsonObject.
So the easiest would be to cast the returnvalue (in JSON) to the JsonObject.
In your case this should be something like:
<!-- language-all: C# -->
dynamic response = client.Get("me", new { fields = "verified, picture" });
string url = response.picture.data.url;
I'm not entirely sure which Json library you are using, but perhaps try this:
fbPicture = response["picture"]["data"]["url"].ToString();
Related
I'm new to the REST API world. I explain my need: at a specific URL I have a raw JSON text, I would like this text to be acquired by my application and inserted later in the DB as a model I created previously through EF. C# NET-CORE 2.2.
if I wasn't clear enough, don't hesitate to ask me for more details.
Thanks in advance!
Edit:
I'm sorry if it' was unclear, I will provide more detail:
Actually, i have a JSON string downloaded from an url. I did it with the following code:
var client = new WebClient();
var jsonFull = client.DownloadString(string.Format("https://url"));
It's working fine. Now, I need to take from this string only a little part of the JSON, so i did:
using var jsonDoc = JsonDocument.Parse(jsonFull);
var jsonParsed = jsonDoc.RootElement;
var myCV = jsonParsed.GetProperty("cv");
CVE is an object of this JSON, and I succesfully take it.
Inside this object, there is another one called CV_data, so I extract this:
var myCVLE = myCV.GetProperty("CV_data_meta");
The result is a var with inside
ValueKind = Object : "{
"ID": "CV-2019",
"ASS": "cv#ms.org"
}"
Now, I have a class like that
public class CV_data_meta
{
[JsonPropertyName ("ID")]
public string ID { get; set; }
[JsonPropertyName("ASS")]
public string ASS { get; set; }
}
The question is: how i can put the value in the var myCVLE in the class CV_data_meta?
I tried with
var myCVClass = JsonSerializer.Deserialize<CV_data_meta>(myCVLE);
But I get an error.
Note: I can't deserialize all the string JSON into an object, because there are a lot of information that I don't need.
Thanks in advance all!
As I understand from your question, it follows:
You first need to create the JSON object mapping (class) that the API URL will return.
Then consume the API url like this:
var client = new WebClient();
var reply =
client.DownloadString(
string.Format("https://www.yourapi.com/yourpath?yourkey={0}", yourkey));
receive and map object with mapped class
var yourvar = JsonConvert.DeserializeObject<yourclass>(reply);
Now you have the API return mapped to a class in your application, you can do whatever you want with it, including saving to a database.
I am using Sql Database rest api via c# code.
I am looking for a way to added the json to the body.
This is the format required.
{
"properties":
{
"startIpAddress": "0.0.0.3",
"endIpAddress": "0.0.0.3"
}
}
link. https://learn.microsoft.com/en-us/rest/api/sql/firewallrules/createorupdate
I'n not so used to doing this type procedure.
So, do I need to add the root 'properties' in the call? If so, how do I nest the json into the code?
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
startIpAddress = ip,
endIpAddress = ip
});
streamWriter.Write(json);
}
I tried this, but got bad format error back.
Many thanks in advance
Scott
For the required output json you should have something link this as your anonymous object:
new
{
properties = new {
startIpAddress = ip,
endIpAddress = ip
}
}
Now it would have the properties as main object and inside it two properties that you need.
I am using the Google C# API for the Custom Search and have it working and returning results, however I cannot see a way to make the paging work correctly.
Looking at what I get returned, no where does it tell me how many pages there are in the result? It just has a .Start property? Which is not much good unless I know how many 'pages' of results I have?
Am I missing something stupid here? Here is an example of the code I have so far
var svc = new CustomsearchService(new BaseClientService.Initializer { ApiKey = settings.GoogleCustomSearchApi });
var listRequest = svc.Cse.List(searchTerm);
listRequest.Cx = settings.GoogleCustomSearchEngineId;
listRequest.ImgSize = CseResource.ListRequest.ImgSizeEnum.Medium;
listRequest.Num = 10;
// List to hold everything in
var resultItems = new List<Google.Apis.Customsearch.v1.Data.Result>();
// Result set 1
listRequest.Start = 1;
var search = listRequest.Execute();
resultItems.AddRange(search.Items);
I have resulted at the moment to doing two or three calls one after the other and getting a load of results back. But I would prefer to have this properly paged.
The JSON API response has totlResults field:
https://developers.google.com/custom-search/json-api/v1/reference/cse/list#response.
It should be exposed under search.Queries
Found it, its in
search.SearchInformation.TotalResults
I'm using Facebook C# API and I want to create a custom "Like" action, allowing the user to like objects outside of Facebook.
The user will be allowed to "Like" a custom object, like an Apple or a Book, and the app has to post this information in the user timeline.
I've tried
dynamic res = fb.Post("me/og.likes", new
{
message = "My first like post using Facebook SDK for .NET"
});
But this gives me the following FacebookApiException exception
(Exception - #1611072) The action you're trying to publish is invalid because it does not specify any reference objects. At least one of the following properties must be specified: object.
But if I try
dynamic res = fb.Post("me/og.likes", new
{
object="http://samples.ogp.me/226075010839791"
});
it doesn't even compile, since object is a reserved word on C#.
What should I do?
Is it possible?
Try escape using #:
dynamic res = fb.Post("me/og.likes", new
{
#object="http://samples.ogp.me/226075010839791"
});
EDIT: For other special characters you should be able to use a dictionary instead of a anonymous typed object:
var postInfo = new Dictionary<string, object>();
postInfo.Add("fb:explicitly_shared", "your data");
dynamic res = fb.Post("me/og.likes", postInfo);
I'm trying to create a simple iFrame custom tab on my fan page. I'm using the Facebook C# SDK and I need to read the signed_request value that Facebook passes to my iFrame page.
I can print the signed_request encoded value so I know its showing up, but when I try to decode it with the Facebook C# SDK I'm getting an error. I'm using .NET 4.0 and dynamics.
Here's my code:
signedRequestString contains the Request value with the signed_param passed from Facebook.
var result = FacebookSignedRequest.Parse(FacebookContext.Current.AppSecret, signedRequestString);
dynamic signedRequestJson = result.Data;
dynamic page = signedRequestJson.page;
And the error I receive:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference at CallSite.Target(Closure , CallSite , Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0) at DecodeSignedRequest(String signedRequestString)
Any thoughts why I would be getting a null? I setup my web.config properly (I think), but I'm guessing I'm missing an initialization step or something.
It's easier to use FacebookWebContext.Current.SignedRequest.
You can then access the information about the page:
if (FacebookWebContext.Current.SignedRequest != null)
{
dynamic data = FacebookWebContext.Current.SignedRequest.Data;
if (data.page != null)
{
var pageId = (String)data.page.id;
var isUserAdmin = (Boolean)data.page.admin;
var userLikesPage = (Boolean)data.page.liked;
}
else
{
// not on a page
}
}
You need to cast your signedRequestJson object to an IDictionary key/value pair before you can grab the page data.
You can do this as follows:
dynamic signedRequestJson = result.Data;
var RawRequestData = (IDictionary<string, object>)signedRequestJson;
You can then access the page data using the JSON keys (assuming you are referencing the Newtonsoft.Json.dll library):
Facebook.JsonObject RawPageData = (Facebook.JsonObject)RawRequestData["page"];
currentFacebookPageID = (string)RawPageData["id"];
Hope this helps.
I am using this. I hope it works for you:
Facebook.FacebookConfigurationSection s = new FacebookConfigurationSection();
s.AppId = 'ApplicationID';
s.AppSecret = 'ApplicationSecret';
FacebookWebContext wc = new FacebookWebContext(s);
dynamic da = wc.SignedRequest.Data;
dynamic page = da.page;
string pageid = page.id;
bool isLiked = page.liked;
bool isAdmin = page.admin;