-3

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 enter image description here

jpf911
  • 117
  • 2
  • 9
  • " an error when I try to serialize or update a json file" serialize or update? I never heard about a serialize error. Can you post an error message pls? – Serge May 12 '22 at 22:51

1 Answers1

3

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);
Serge
  • 40,935
  • 4
  • 18
  • 45
  • I think his file path is stored in Login.jsonResponse, which would obviously fail to deserialize `User[]? Users = JsonConvert.DeserializeObject(Login.jsonResponse)` – ScottyD0nt May 12 '22 at 23:05
  • @ScottyD0nt Then it would be a newtonsoft.json DeserializeObject error, but it is a save file error. – Serge May 12 '22 at 23:30
  • yeah, I didn't see the exception that got added to the post. looks like you got it right. – ScottyD0nt May 12 '22 at 23:32