繁体   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