无法写入 json 变量 c# 出现错误
Unable to Write json variable c# getting an error
我在尝试序列化或更新 json 文件时遇到错误。我只想更新 json 文件中 "balance" 的值,我想到了 ...我似乎做不到为我的项目工作。 Users.json 文件每次检查都没有改变。
这是我的代码:
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
你有一个错误
File.WriteAllText(Login.jsonResponse, json);
而不是 ogin.jsonResponse 你必须使用文件路径
File.WriteAllText(<full file path\Users.json>, json);
我在尝试序列化或更新 json 文件时遇到错误。我只想更新 json 文件中 "balance" 的值,我想到了
这是我的代码:
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
你有一个错误
File.WriteAllText(Login.jsonResponse, json);
而不是 ogin.jsonResponse 你必须使用文件路径
File.WriteAllText(<full file path\Users.json>, json);