简体   繁体   English

将类序列化为 .json 文件

[英]Serializing class to .json file

just trying to do a simple serialize(first time trying).只是想做一个简单的序列化(第一次尝试)。 actually had this working up until I changed a few things and added a deserialize and added a class that made my other way no longer work.直到我改变了一些东西并添加了反序列化并添加了一个使我的其他方式不再起作用的类之前,实际上已经开始工作了。

basically I took what I had for deserialize json to object and tried to just reverse the order of things.基本上,我将反序列化 json 的内容用于对象,并试图颠倒事物的顺序。 but now I get an error at a foreach loop I'm not sure if I even need.但现在我在 foreach 循环中遇到错误,我不确定是否需要。 Once I get the serialize working I'm sure I will also be stuck on how to format the string as it enters the .json file so it appends properly but that is for another day.一旦我让序列化工作,我相信我也会在字符串进入 .json 文件时被困在如何格式化字符串上,以便它正确附加,但那是另一天。

here is error i received这是我收到的错误

System.NullReferenceException: 'Object reference not set to an instance of an object.' System.NullReferenceException: '未将对象引用设置为对象的实例。'

i receive this exception on the line foreach(var translogs in Logs.transLogs)我在foreach(var translogs in Logs.transLogs)行上收到此异常foreach(var translogs in Logs.transLogs)

here is my event.这是我的活动。

Code代码

private void toolPull_Click(object sender, EventArgs e)
{
    double cost = Convert.ToDouble(active_Cost.Text);
    int serial = Convert.ToInt32(transactionSerial_Box.Text);
    DateTime timeNow = DateTime.Now;
    TransactionLogs Logs = new TransactionLogs();
    foreach(var translogs in Logs.transLogs)
    {
        translogs.Employee = transactionEmployee_Box.Text;
        translogs.Serial = serial;
        translogs.Cost = cost;
        translogs.Description = active_Description.Text;
        translogs.CurrentDate = timeNow;
    }

    string stringJson = JsonConvert.SerializeObject(Logs);
    StreamWriter sw = new StreamWriter(@"C:\transactionlog.json", append: true);
    sw.WriteLine(stringJson);
    sw.Close();
}

Here is the class to work with json这是使用 json 的类

namespace QuickType
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class TransactionLogs
    {
        [JsonProperty("TransactionLog")]
        public List<TransactionLog> transLogs { get; set; }
    }

    public partial class TransactionLog
    {
        [JsonProperty("employee")]
        public string Employee { get; set; }

        [JsonProperty("currentDate")]
        public DateTime CurrentDate { get; set; }

        [JsonProperty("serial")]
        public int Serial { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }

        [JsonProperty("isPull")]
        public bool IsPull { get; set; }

        [JsonProperty("cost")]
        public double Cost { get; set; }
    }
}

and here is json file这是json文件

{
   "TransactionLog":[
      {
         "employee":"Joey",
         "currentDate":"2021-11-03T11:49:13.5741628-04:00",
         "serial":1111,
         "description":"1/2-20 Threadmill",
         "isPull":true,
         "_ost":25.68
      },
      {
         "employee":"joey",
         "currentDate":"2021-11-03T11:50:34.6344474-04:00",
         "serial":1000,
         "description":"1/2-20 Threadmill",
         "isPull":true,
         "cost":25.68
      },
      {
         "employee":"john",
         "currentDate":"2021-11-03T11:50:40.9956616-04:00",
         "serial":2000,
         "description":"1/2-20 Threadmill",
         "isPull":true,
         "cost":25.68
      },
      {
         "employee":"Jim",
         "currentDate":"2021-11-03T11:51:24.5559292-04:00",
         "serial":4565,
         "description":"1/2-20 Threadmill",
         "isPull":true,
         "cost":25.68
      }
   ]
}

Let me capture here the outcome of the comments.让我在这里记录评论的结果。

There were two problems with these two lines:这两行有两个问题:

TransactionLogs Logs = new TransactionLogs();
foreach(var translogs in Logs.transLogs)
  • The TransactionLogs 's transLogs collection is not initialized, that's caused the NRE TransactionLogstransLogs集合未初始化,这导致了 NRE
  • After fixing that the foreach went through on an empty collection在修复了foreach在一个空集合上经历的问题之后

The fix for the first problem:第一个问题的修复:

Logs.transLogs = new List<TransactionLog>();

The fix for the second problem:第二个问题的修复:

var transLogs = new TransactionLog()
{
    Employee = transactionEmployee_Box.Text;
    Serial = serial;
    Cost = cost;
    Description = active_Description.Text;
    CurrentDate = timeNow;
};
Logs.transLogs.Add(transLogs);

So, rather than iterating through the empty collection, you had to populate it by adding a new member.因此,您必须通过添加新成员来填充它,而不是遍历空集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM