c# .net - read JSON - c#

I am trying to read an environment variable from a JSON object that looks like this:
{
"staging_env_json": {},
"running_env_json": {},
"system_env_json": {
"EN_VAR_NAME": {
"mysql": [
{
"name": "name-here",
"label": "label-here",
"tags": [
"mysql",
"relational"
],
"plan": "",
"credentials": {
"hostname": "host",
"port": "port",
"name": "name-here",
"username": "username",
"password": "password",
}
}
]
}
}
}
Using C# how would I access the username and password? I have tried this....
envVariable = Environment.GetEnvironmentVariable("EN_VAR_NAME");
var obj = JObject.Parse(envVariable);
var hostname = (string)obj["mysql"]["credentials"]["username"];
But this isn't getting me where.. can anyone please point me in the right direction?

dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(envVariable);
var userName = ((dynamic)obj).system_env_json.EN_VAR_NAME.mysql[0].credentials.username

You can parse it as dynamic:
dynamic result = JsonConvert.DeserializeObject<dynamic>(input);
Console.WriteLine(result.system_env_json.EN_VAR_NAME.mysql[0].credentials.username);

Related

Parse nested json and return the values as string[]

Can you help me parse the values in 'realEstateProperties' attribute (ex. serial number and economyType.value). Here is a part of the json file:
{
"Entity1": {
"id": "5f514d20744a1fb",
"realEstateProperties": [
{
"serialNumber": "11",
"cadastralSections": [
{
"id": "5f514dc11a1e3",
"economyType": {
"value": "landRegisterPage.type",
}
}
],
"landRegisterPage": {
"id": "3456",
"landRegisterBook": {
"abbreviation": null
},
"note": "LRP",
"tags": null
},
"propertyTextBlock": null
}
],
"customFields": [],
Here is what I currently have:
public static string[] GetJsonValues(string jsonProperty)
{
testCaseName = "Entity1";
FixtureIncident.Root incObject = new FixtureIncident.Root();
incObject = LoadJSONFile();
JObject incJson = JObject.FromObject(incObject);
var attributes = incJson[testCaseName].ToList<JToken>();
var property = attributes.Find(i => i.ToObject<JProperty>().Name == jsonProperty) as JArray; //returns property=null
string[] Properties = property.ToObject<string[]>();
return Properties;
}
property returns null and I am not sure how to correct it.
I need to save all the realEstateProperties values in a string[].
I found some similar topics but I couldn't adjust my code so I make it works. Thanks in advance for your help.

How to filter out string

How do i filter out to obtain the text ("I can provide....")? The program im using has no variable that contains just this text. Thanks!
{
"session_id": "9643039c-edf0-435a-8345-fc225859a6de"
}
{
"output": {
"generic": [
{
"response_type": "text",
"text": "I can provide you with directions, locations and operating hours as of now."
}
],
"intents": [
{
"intent": "Function",
"confidence": 0.30141472287041043
}
],
"entities": []
}
}
{}
Thanks...took me longer than it should have but here it the code:
string response = dialog.Message();
JObject data = JObject.Parse(response);
Console.WriteLine(data["output"]["generic"].First["text"]);
string text = data["output"]["generic"].First["text"].ToString();

Unity Facebook SDK, retrieve data from 'apprequests' from API

I am fetching /me/apprequests from Facebook API. It works and I get the data in JSON format.
Thing is that everything is nested, like a dictionary inside a dictionary.
What i tried:
Dictionary<string, object> dict = Facebook.MiniJSON.Json.Deserialize(result.RawResult) as Dictionary<string, object>;
object data;
string request_code = "";
if (dict.TryGetValue("data", out data))
{
var rc = (((Dictionary<string, object>)data)["id"]);
request_code = (string)rc;
}
Debug.Log("request_code=" + request_code);
I think I need to loop the dictionary to get all id's.
I can confirm that if (dict.TryGetValue("data", out data)) does work correctly and get the dictionary of data arrays, but fails here (((Dictionary<string, object>)data)["id"]); with casting error.
Json looks like:
{
"data": [{
"application": {
"category": "Games",
"link": "https:\/\/www.facebook.com\/games\/?app_id=2523532533",
"name": "game name",
"id": "23432423423"
},
"created_time": "2019-02-27T16:01:15+0000",
"from": {
"name": "David boom",
"id": "387923432423089962"
},
"message": "You are invited",
"to": {
"name": "Dusty Spice",
"id": "10234324421033685"
},
"id": "413880842521239_10156578101000000"
},
{
"application": {
"category": "Games",
"link": "https:\/\/www.facebook.com\/games\/?app_id=2523532533",
"name": "game name",
"id": "23432423423"
},
"created_time": "2019-02-27T14:12:41+0000",
"from": {
"name": "David boom2",
"id": "387923432423089962"
},
"message": "You are invited",
"to": {
"name": "Dusty Spice",
"id": "10234324421033685"
},
"id": "316676422209302_10156578101000000"
}],
"paging": {
"cursors": {
"before": "NDEzODgwODQyNTIxMjM5Ojc1OTQzODY4NAZDZD",
"after": "MzE2Njc2NDIyMjA5MzAyOjc1OTQzODY4NAZDZD"
}
}
}
Managed to make it work if it will help someone:
string request_code = "";
if (dict.TryGetValue("data", out data))
{
int dataLength = ((List<object>)data).Count;
for (int i = 0; i < dataLength; i++)
{
var rc = ((List<object>)data)[i];
var rc2 = (((Dictionary<string, object>)rc)["id"]);
request_code = (string)rc2;
Debug.Log("request_code=" + request_code);
}
}

get Specific Id from json file

this is my json file
{
{
"#odata.context": "https://api.onedrive.com/v1.0/$metadata#drives('me')/items('root')/children/$entity",
"createdBy": {
"application": {
"displayName": "Nopbackup",
"id": "4c190e01"
},
"user": {
"displayName": "pallav jha",
"id": "611c19eb038d5aa1"
}
},
"createdDateTime": "2016-05-12T07:25:36.463Z",
"cTag": "adDo2MTFDMTlFQjAzOEQ1QUExITEyNC42MzU5ODYzODk5MTI3MDAwMDA",
"eTag": "aNjExQzE5RUIwMzhENUFBMSExMjQuMw",
"id": "611C19EB038D5AA1!124",
"lastModifiedBy": {
"application": {
"displayName": "Nopbackup",
"id": "4c190e01"
},
"user": {
"displayName": "pallav jha",
"id": "611c19eb038d5aa1"
}
},
"lastModifiedDateTime": "2016-05-12T08:36:31.27Z",
"name": "Nopbackup",
"parentReference": {
"driveId": "611c19eb038d5aa1",
"id": "611C19EB038D5AA1!105",
"path": "/drive/root:"
},
"size": 0,
"webUrl": "https://onedrive.live.com/redir?resid=611C19EB038D5AA1!124",
"fileSystemInfo": {
"createdDateTime": "2016-05-12T07:25:36.463Z",
"lastModifiedDateTime": "2016-05-12T08:36:31.27Z"
},
"folder": {
"childCount": 0
}
}
}
i want to get this "id": "4c190e01" from json
dynamic value = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
string id = Convert.ToString(value.id[0]);
this is my code but i am not getting 4c190e01 id
rewrite your code as following...
dynamic valuePoco = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
string id = Convert.ToString(valuePoco.createdBy.application.id);
You can use the path to the desired property. If you want to select the element with 4c190e01 as id, you can use
string id = value.createdBy.application.id;
or
string id = value.lastModifiedBy.application.id;
depending on your needs.
As it was pointed out, you'd need to fix your JSON first and remove the first { and the last }
First thing first, Your json is invalid.
You've to remove one { from top and } from the bottom and then use the following code:
dynamic jsonObj = JsonConvert.DeserializeObject(result);
string id = jsonObj.createdBy.application.id.ToString();

Something wrong with passing parameter to FB Api() method

I've the following code that fetches my friends list with some specific fields to be returned.
public ActionResult Test()
{
fbApp = new FacebookApp();
authorizer = new CanvasAuthorizer(fbApp);
authorizer.Perms = requiredAppPermissions;
if (fbApp.Session != null)
{
dynamic friendsFields = new ExpandoObject();
friendsFields.fields = "id,name,location,bio,gender,religion,activities";
JsonObject data = fbApp.Get("/me/friends", friendsFields);
ViewData["friends"] = data["data"] as JsonArray;
return View();
}
}
I'm asking for id,name,location,bio,gender,religion,activities fields, but the result doesn't submit all those fields. Only id,name,gender are returned which makes suspect something is wrong... if i try to get the same data using the browser and passing the fields the result returns all the requested fields:
URL: https://graph.facebook.com/me/friends?fields=id,name,bio,gender,picture,religion,activities&access_token=...
"data": [
{
"id": "data_data_data",
"name": "data_data_data",
"bio": "data_data_data",
"gender": "data_data_data",
"religion": "data_data_data",
"picture": "data_data_data",
"activities": {
"data": [
{
"name": "data_data_data",
"category": "data_data_data",
"id": "data_data_data",
"created_time": "data_data_data"
}
]
}
},
{
"id": "data_data_data",
"name": "data_data_data",
"bio": "data_data_data",
"gender": "data_data_data",
"picture": "data_data_data"
}
]
}
Anyone have any idea what might be wrong here? Can it be the API? I'm using the latest version 4.1.1
TIA!
You have to cast the result of the Get method or just access it dynamically. Here is the corrected code with the authorization fixed as well.
[CanvasAuthorize(Perms="user_friends")]
public ActionResult Test()
{
var fbApp = new FacebookApp();
dynamic friendsFields = new ExpandoObject();
friendsFields.fields = "id,name,location,bio,gender,religion,activities";
dynamic result = fbApp.Get("/me/friends", friendsFields);
var data = result.data as JsonArray;
ViewData["friends"] = data;
return View();
}

Categories

Resources