'Unable to Write json variable c# getting an error
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);
}
Solution 1:[1]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Serge |