簡體   English   中英

C# JSON 文件反序列化為多個對象

[英]C# JSON file deserialized into multiple objects

這是我在 Stackoverflow 上的第一個問題。 我正在學習 C#,我在 C# 中構建了一個簡單的銀行控制台應用程序。創建了一個小菜單,其中一個選項是允許用戶創建銀行帳戶,並將其保存在 json 文件中。

保存到 json 文件中的用戶輸入示例如下:

{
    "FirstName": "Ari",
    "LastName": "Man",
    "Pin": 1122,
    "Balance": 400.0
}
{
    "FirstName": "Tari",
    "LastName": "Man",
    "Pin": 3434,
    "Balance": 566.89
}
{
    "FirstName": "Mari",
    "LastName": "Man",
     "Pin": 5656,
    "Balance": 677.0
}

我的代碼是:

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Remoting;
using Newtonsoft.Json;

namespace BankApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string selection;
            //int _initPin;
            double newBalance;

            //create bank object
            Accounts bank = new Accounts();

            //display menu
            while (true)
            {
                Console.WriteLine("=======================================");
                Console.WriteLine("Welcome to Banko - your online Bank App");
                Console.WriteLine("=======================================\n");
                Console.WriteLine("1. Account Balance\n");
                Console.WriteLine("2. Open an account\n");
                Console.WriteLine("3. Withdraw\n");
                Console.WriteLine("4. Deposit\n");
                Console.WriteLine("5. Exit\n\n");

                Console.WriteLine("Select an option:\n ");
                selection = Console.ReadLine();

                if (selection == "5")
                {
                    Console.WriteLine("Thank You! Hope to see you soon");
                    Console.ReadLine();
                    break;
                }
                else
                    switch (selection)
                    {
                        case "1":
                            Console.WriteLine(Deserialize());
                            break;

                        case "2":
                            Console.WriteLine("Enter your first name: ");
                            bank.FirstName = Console.ReadLine();
                            Console.WriteLine("Enter your last name: ");
                            bank.LastName = Console.ReadLine();
                            Console.WriteLine("Enter a new new PIN: ");
                            bank.Pin = int.Parse(Console.ReadLine());
                            Console.WriteLine("Enter starting balance: ");
                            bank.Balance = double.Parse(Console.ReadLine());
                            break;

                        case "3":
                            newBalance = bank.Withdraw();
                            Console.WriteLine("Your current balance is: {0}", newBalance + Environment.NewLine);
                            break;

                        case "4":
                            newBalance = bank.Deposit();
                            Console.WriteLine("Your current balance is: {0}", newBalance + Environment.NewLine);
                            break;
                    }
            }


            //serialize JSON file and write to json file
            string filePath = @"C:\Users\shakazul\source\repos\BankApp\accounts.json";
            string output = JsonConvert.SerializeObject(bank, Formatting.Indented);
            File.AppendAllText(filePath, output + Environment.NewLine);
        }

        public static Accounts Deserialize()
        {
            //path to JSON file and read file
            string filePath = @"C:\Users\shakazul\source\repos\BankApp\accounts.json";
            string jsonResults = File.ReadAllText(filePath);

            //Deserialize the JSON file to an object
            Accounts results = JsonConvert.DeserializeObject<Accounts>(jsonResults);
            return results;
        }
    }
}

我的 class 是:

namespace BankApp
{
    public class Accounts
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Pin { get; set; }
        public double Balance { get; set; }

        public Accounts()
        {
            this.FirstName = FirstName;
            this.LastName = LastName;
            this.Pin = Pin;
            this.Balance = Balance;
        }
   
        public double Deposit()
        {
            double deposit;
            double newBalance;

            Console.WriteLine("Please enter amount to deposit: ");
            deposit = double.Parse(Console.ReadLine());

            newBalance = Balance + deposit;

            return newBalance;
        }

        public double Withdraw()
        {
            double newBalance;
            double withdraw;

            Console.WriteLine("Please enter amount to withdraw: ");
            withdraw = double.Parse(Console.ReadLine());

            newBalance = Balance - withdraw;

            return newBalance;
        }
    }
}

所以我的問題是,當我解析 json 文件並根據他們輸入的 PIN 獲取某個客戶的賬戶余額時,我收到一個錯誤

Newtonsoft.Json.JsonReaderException: '閱讀完 JSON 內容后遇到的附加文本:{。 路徑 '',第 6 行,}

因此,如果我只有一個條目,我可以檢索余額值,但不止於此,我會得到發生在以下位置的錯誤:

Accounts results = JsonConvert.DeserializeObject<Accounts>(jsonResults); 

代碼行。

任何幫助將不勝感激。

您要處理的主要問題是您試圖通過手動附加它而不是將對象集合序列化為 JSON 來創建 JSON。

解釋一下,當您保存新對象時,它們看起來像這樣:

//JsonDeserializer reads this as start of document.
{ "FirstName": "Ari",
  "LastName": "Man",
  "Pin": 1122,
  "Balance": 400.0 
} 
//JsonDeserializer reads this as end of document.

{ //Document already ended, what to do with this??? JsonDeserializer throws exception. 
"FirstName": "Tari",
  "LastName": "Man",
  "Pin": 3434,
  "Balance": 566.89 
} 
{ "FirstName": "Mari",
  "LastName": "Man",
  "Pin": 5656,
  "Balance": 677.0
}

這不是有效的 JSON(也不是單個有效的 JSON 文檔)。 JSON 序列化程序無法檢測到第二個 object,因為沒有任何信息告訴他們在那里期待object。 相反,您要做的是獲取所有對象並將它們放入一個數組中,就像這樣。

[
{"FirstName: "Ari", "Last"...}, //the commas tell the deserializer to expect more objects
{"FirstName: "Tari", "Last"...},
{"FirstName: "Mari", "Last"...}
]

但是,您不必手動執行此操作。 當你序列化一個 object 時,Newtonsoft.Json 會自動為你構建 JSON。你需要做的是告訴 Newtonsoft 你想要一個數組。 為此,將您的 Accounts object 放入一個 Collection 中,例如List

var accounts = new List<Accounts>();
accounts.Add(bank);

然后您可以將此列表序列化為 JSON 並保存,然后可以將此列表反序列化回列表。 您可以向其中添加更多帳戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM