【问题标题】:asp.net c# to json how to store data without overwriting existing dataasp.net c#转json如何在不覆盖现有数据的情况下存储数据
【发布时间】:2017-10-05 10:25:16
【问题描述】:

所以我在 JSON 文件和 C# 之间转换数据时遇到了很多麻烦。到目前为止,我可以通过一个很棒的 Asp.net 表单轻松地将数据添加到 JSON 文件,但它会覆盖那里的任何现有数据,基本上我想添加到文件中而不发生这种情况。

下面是我想要实现的 C# 代码。我相信我已经很接近了,正如您所看到的,我尝试在添加之前将 JSON 文件放入一个字符串中,然后在通过单独的字符串添加新数据后将它们都添加回文件中,但这不起作用。

注意:我是新手,我已经在这个网站和谷歌上研究了几个小时甚至几天,试图了解我哪里出错了,因为我知道这非常容易,但我就是不明白。

public partial class AddBook : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    const string FILENAME = "Books.json";
    string fullFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FILENAME);

    string jsonText2 = File.ReadAllText(fullFileName);
    BookCollection bookCollection2 = JsonConvert.DeserializeObject<BookCollection>(jsonText2);

    if (!Page.IsPostBack)
    {

        if (Session["EditDetails"] != null && (Boolean)Session["editDetails"] == true)
        {
            BookYear(DDLYear);
        }
        else
        {
            BookYear(DDLYear);
        }
    }
    else if(IsPostBack) {


            String BookID = TxtBookID.Text;
            String Title = TxtTitle.Text;
            String Author = TxtAuthor.Text;
            String Year = DDLYear.Text;
            String Publisher = TxtPublisher.Text;
            String ISBN = TxtISBN.Text;

            BookCollection bookCollection = new BookCollection();

            Book book = new Book(BookID, Title, Author, Year, Publisher, ISBN);
            bookCollection.books.Add(book);


            string jsonText = JsonConvert.SerializeObject(bookCollection);
            File.WriteAllText(fullFileName, jsonText);
            jsonText2 = JsonConvert.SerializeObject(bookCollection);


    }
}
protected void BookYear(DropDownList dropDownList)
{
    int yr = DateTime.Now.Year;
    dropDownList.Items.Insert(0, "Select Year");
    for (int x = 1900; x < yr; x++)
    {
        dropDownList.Items.Add(x.ToString());
    }
}

protected void BtnSubmit_Click(object sender, EventArgs e)
{

    Response.Redirect(Request.RawUrl);
    //String BookID = TxtBookID.Text;
    //String Title = TxtTitle.Text;
    //String Author = TxtAuthor.Text;
    //String Year = DDLYear.Text;
    //String Publisher = TxtPublisher.Text;
    //String ISBN = TxtISBN.Text;

    //const string FILENAME = "Books.json";
    //string fullFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FILENAME);

    //BookCollection bookCollection = new BookCollection();

    //Book book = new Book(BookID, Title, Author, Year, Publisher, ISBN);
    //bookCollection.books.Add(book);

    //string jsonText = JsonConvert.SerializeObject(bookCollection);
    //File.WriteAllText(fullFileName, jsonText);

}

}

我也有单独的课程

public class Book
{

public String id { get; set; }
public string title { get; set; }
public string author { get; set; }
public String year { get; set; }
public string publisher { get; set; }
public String isbn { get; set; }

public Book(String id, string title, string author, String year, string 
publisher, String isbn)
{
    this.id = id;
    this.title = title;
    this.author = author;
    this.year = year;
    this.publisher = publisher;
    this.isbn = isbn;
}

public class BookCollection
 {

public List<Book> books { get; set; }

public BookCollection()
{
    this.books = new List<Book>();
}


}

【问题讨论】:

  • 您查看过File.WriteAllText 的文档吗?也许你应该从那里开始:Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.
  • 需要将 json 附加到文件的步骤是: 1) 获取要附加的内容。 2) 将现有内容读回内存 3) 合并数据结构 4) 将合并后的结构写回文件(现在您可以使用File.WriteAllText)。

标签: c# asp.net json webforms


【解决方案1】:

我不确定为什么要保留以前的序列化数据,因为在写入新数据时它应该是“旧的”。但是,如果您查看the documentation for File.WriteAllText(强调我的):

创建一个新文件,将指定的字符串写入文件,然后 关闭文件。如果目标文件已经存在,将被覆盖

你有几个选择:

  1. 读取当前文本并使用File.WriteAllText将其全部写入
  2. 使用其他File 方法,例如File.AppendText

创建一个 StreamWriter,将 UTF-8 编码的文本附加到现有的 文件,如果指定的文件不存在,则转到新文件。

但是,如果您想将所有 BookCollection 作为文件列表保留,我建议您将文件作为 List&lt;BookCollection&gt; 写入/读取,这样您就不必考虑处理不同的对象。

【讨论】:

  • AppendText 在下次反序列化时不会产生可用对象
  • @KyleBurns 我很清楚这一点,这就是我回答的最后一部分的原因。
  • file.appendtext...多么美丽。现在它添加到文件而不删除。谢谢你。我相信你答案的最后一部分是指现在在 JSON 文件中它每次都会创建一本新书,这是不允许的。我看到了问题,但我缺乏真正解决问题的技能。我可以看到你也给出了这个问题的答案,但我真的不明白。但是我会使用代码,直到这个 List 工作。非常感谢
猜你喜欢
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多