-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

1
  • " 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? Commented May 12, 2022 at 22:51

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I think his file path is stored in Login.jsonResponse, which would obviously fail to deserialize User[]? Users = JsonConvert.DeserializeObject<User[]>(Login.jsonResponse)
@ScottyD0nt Then it would be a newtonsoft.json DeserializeObject error, but it is a save file error.
yeah, I didn't see the exception that got added to the post. looks like you got it right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.