I get an error when I try to serialize or update a json file. I just want to update the value of "balance" inside a json file and I got the idea here... I can't seem to make it work for my project. The Users.json file does not change whenever I check it.
here is my code:
Users.json
[
{
"id": 1,
"username": "sachin",
"password": "sachin1",
"firstName": "Sachin",
"lastName": "Karnik",
"birthdate": "2011-6-14",
"balance": 20000,
"cardNumber": 12345
},
{
"id": 2,
"username": "dina",
"password": "dina1",
"firstName": "Dina",
"lastName": "Meyers",
"birthdate": "2012-8-20",
"balance": 20000,
"cardNumber": 23456
},
{
"id": 3,
"username": "andy",
"password": "andy1",
"firstName": "Andy",
"lastName": "Rose",
"birthdate": "2010-2-11",
"balance": 20000,
"cardNumber": 34567
}
]
Menu.cs
public static void BankMenu(object? balance, object? user)
{
User[]? Users = JsonConvert.DeserializeObject<User[]>(Login.jsonResponse);
int bal = Convert.ToInt32(balance);
int money;
try{
money = ValidateAmountInput(bal, user);
if (money <= bal && money != 0)
{
bal -= money;
foreach (var usr in Users!)
{
if (usr.FirstName == user?.ToString())
{
usr.Balance = bal;
}
}
var json = JsonConvert.SerializeObject(Users, Formatting.Indented);
File.WriteAllText(Login.jsonResponse, json);
}
}
catch(System.Exception e)
{
WriteLine(e);
}
My Error
you have a bug
File.WriteAllText(Login.jsonResponse, json);
instead of ogin.jsonResponse you have to use a file path
File.WriteAllText(<full file path\Users.json>, json);
Related
I am trying to filter nested data but the catch is, the children I am also trying to filter are of a different type.
I have data that looks like this:
{
"value": [
{
"UserName": "scottketchum",
"FirstName": "Scott",
"LastName": "Ketchum",
"MiddleName": null,
"Gender": "Male",
"Age": null,
"Emails": [
"Scott#example.com"
],
"FavoriteFeature": "Feature1",
"Features": [],
"AddressInfo": [
{
"Address": "2817 Milton Dr.",
"City": {
"Name": "Albuquerque",
"CountryRegion": "United States",
"Region": "NM"
}
}
],
"HomeAddress": null
},
{
"UserName": "harryingram",
"FirstName": "Harry",
"LastName": "Ingram",
"MiddleName": null,
"Gender": "Male",
"Age": null,
"Emails": [
"Harry#example.com"
],
"FavoriteFeature": "Feature2",
"Features": [],
"AddressInfo": [
{
"Address": "123 Scott Ln.",
"City": {
"Name": "Nashville",
"CountryRegion": "United States",
"Region": "TN"
}
}
],
"HomeAddress": null
}
]
}
I need to be able to type the word "Scott" in my search field and return any person that has the name "Scott" or has an Address with the word "Scott" in it. So, ideally, the search would return both people.
void searchitemfromjson(string s)
{
var text = File.ReadAllText("D://jsontest.txt");
var jObject1 = JObject.Parse(text)["value"];
var searchs = new List<string>();
foreach (var item in jObject1)
{
var jObjitem = JObject.Parse(item.ToString());
IList<string> keys = jObjitem.Properties().Select(p => p.Name).ToList();
foreach (var k in keys)
{
if (k == "UserName")
{
if (jObjitem[k].ToString().Contains(s)) searchs.Add(jObjitem[k].ToString());
}
else if(k == "AddressInfo")
{
if(jObjitem["AddressInfo"][0]["Address"].ToString().Contains(s)) searchs.Add(jObjitem[k].ToString()); ;
}
}
}
}
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);
}
}
Not sure how to do the location with a room in C# and Microsoft.Graph.
I want to create an event that would put the event in a room. I now the room’s email - Rainier#M365x947151.onmicrosoft.com . The code I am trying is as follows using Microsoft.Graph.
Microsoft.Graph.PhysicalAddress address = new Microsoft.Graph.PhysicalAddress();
Microsoft.Graph.Location loc = new Location();
loc.Address = address;
loc.DisplayName = "Rainier conf room";
loc.LocationEmailAddress = rainier;
var newEvent = new Event();
newEvent.Subject = subject + DateTime.Now.ToLongDateString();
newEvent.Location = loc;
newEvent.Attendees = attendees;
newEvent.Body = eventBody;
newEvent.Start = eventStartTime;
newEvent.End = eventEndTime;
Microsoft.Graph.Event createdEvent = null;
try
{
// graphclient is passed into this method
// var graphClient = AuthenticationHelper.GetAuthenticatedClient();
// var graphClient = devfish.Graph.AuthenticationHelper.MyGraphClient;
createdEvent = await graphClient.Me.Events.Request().AddAsync(newEvent);
The payload I am sending up SHOULD look something like this, but what it doesn’t look like is below. Outlook doesn’t treat it as a “room”. Thanks…
PAYLOAD WE WANT - note the odatatype and microsoft.graph.physicaladdress ...
{
"subject": "Test meeting",
"body": {
"contentType": "HTML",
"content": "Does this work (note the dates are in the past)?"
},
"start": {
"dateTime": "2017-12-01T12:00:00",
"timeZone": "Pacific Standard Time"
},
"end": {
"dateTime": "2017-12-01T14:00:00",
"timeZone": "Pacific Standard Time"
},
"location":{
"address": {"#odata.type": "microsoft.graph.physicalAddress"},
"displayName": "Rainier conf room"
},
"attendees": [
{
"emailAddress": {
"address":"joseph.healy#microsoft.com",
"name": "Joe"
},
"type": "required"
},
{
"emailAddress": {
"address":"Rainier#M365x947151.onmicrosoft.com",
"name": "Rainier"
},
"type": "Resource"
}
]
}
But instead up payload looks like this when created with C# graph.
{
"subject": "23: 42:39: BASKETBALL IS OUR SUBJECT FOR TODAYTuesday, January 9, 2018",
"body": {
"contentType": "text",
"content": "Status updates, blocking issues, and next steps"
},
"start": {
"dateTime": "2017-12-01T19:30:00.0000000",
"timeZone": "UTC"
},
"end": {
"dateTime": "2017-12-01T20:00:00.0000000",
"timeZone": "UTC"
},
"location": {
"displayName": "Rainier conf room",
"locationEmailAddress": "Rainier#M365x947151.onmicrosoft.com",
"address": {}
},
"attendees": [
{
"type": "required",
"emailAddress": {
"address": "alexw#m365x947151.onmicrosoft.com"
}
},
{
"type": "required",
"emailAddress": {
"address": "maria#fabrikam.com"
}
},
{
"type": "resource",
"emailAddress": {
"address": "Rainier#M365x947151.onmicrosoft.com"
}
}
]
}
Thanks for any help.
To get the payload you want, you'll need to:
Remove loc.LocationEmailAddress = rainier;
Add the key-value "#odata.type", "microsoft.graph.physicalAddress" to
location.AdditionalData. We had someone else recently ask for
automatic #odata.type generation so this is an additional data point
for that.
Add the name property to the room emailAddress object.
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();
I have some problems with jobject and jarray linq query. I get this error:
Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'.
My code:
string fetchResult = JsonConvert.SerializeObject(sidebar, Formatting.Indented);
JObject rss = JObject.Parse(fetchResult);
var jsonModel = from item in (JArray)rss["RegistrationCase"]
select new DataList
{
RegistrationTypeName = item["RegistrationTypeName"].Value<string>(), };
If i remove (Jarray) i get: Cannot access child value on Newtonsoft.Json.Linq.JProperty.
Json, jobject: e.g: i want RegistrationTypeName, FirstName and the value of JournalNumber.
{
"Status": null,
"RegistrationCase": {
"RegistrationTypeName": " ",
"ExpireDate": null,
"PersonId": 7,
"Person": {
"FirstName": " ",
"GenderValue": 2,
"Gender": 2,
},
"UserId": 7,
"User": {
"UserName": "NO-DOM\\wme",
"LastName": null,
"Id": 7,
},
"Transactions": [],
"Comments": [],
"CustomData": [
{
"Key": "JournalNumber",
"Value": "0654-84148-00000-25",
"Id": 3,
},
{
"Key": "IsConsentGiven",
"Value": "False",
"Id": 4,
},
{
],
"FileId": null,
"File": null,
"Id": 7,
}
}
u can get these values directly like :
var RegistrationTypeName = rss["RegistrationCase"]["RegistrationTypeName"];
var FirstName = rss["RegistrationCase"]["Person"]["FirstName"];
var JournalNumber = rss["RegistrationCase"]["CustomData"][0]["Value"];