读取现有的json并添加新记录

时间:2014-12-14 01:04:19

标签: c# json.net

我正在尝试构建一个允许用户将新条目添加到本地json文件的应用程序。我可以轻松地将记录写入文件,但我无法更新它。这是我现在的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
...
public partial class frmGvhs : Form
{
    List<FacultyMember> memberList = new List<FacultyMember>();
    String filename = @"C:\Users\John\test.json";

    public frmGvhs()
    {
        InitializeComponent();
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        FacultyMember member = new FacultyMember();

        member.firstName = txtFirstName.Text;
        member.lastName = txtLastName.Text;
        member.email = txtEmail.Text;
        member.ext = txtExt.Text;
        member.department = cmbDepartments.Text;

        memberList.Add(member);

        String json = JsonConvert.SerializeObject(memberList.ToArray());
        System.IO.File.WriteAllText(filename, json);
    }

    private void frmGvhs_Load(object sender, EventArgs e)
    {
        if (System.IO.File.Exists(filename))
        {
            System.IO.StreamReader re = new System.IO.StreamReader(filename);
            JsonTextReader reader = new JsonTextReader(re);
            JsonSerializer se = new JsonSerializer();
            object parsedData = se.Deserialize(reader);
            String json = JsonConvert.SerializeObject(parsedData);

            Console.Write(json);
        }
    }
}

public class FacultyMember
{
    public String firstName { get; set; }
    public String lastName { get; set; }
    public String email { get; set; }
    public String ext { get; set; }
    public String department { get; set; }

    public FacultyMember()
    {

    }
}

现在,当应用程序加载时,我会看到现有json数据的字符串。所以现在因为它是一个字符串我无法使用它。我是否需要遍历对象[parsedData]?我想基本上将现有数据添加到List<FacultyMember> memberList变量。

2 个答案:

答案 0 :(得分:2)

读取文件内容并反序列化为memberList。然后添加它们并再次保存。

memberList = JsonConvert.DeserializeObject<List<FacultyMember>>(System.IO.File.ReadAllText(filename));

实施例

class Program
    {
        static List<FacultyMember> memberList = new List<FacultyMember>();
        static String filename = @"C:\test.json";
        static void Main(string[] args)
        {
            Save();
            Load();
        }

        static void AddNew()
        {
            FacultyMember member = new FacultyMember();

            member.firstName = "Test";
            member.lastName = "Test";
            member.email = "test";
            member.ext = "test";
            member.department = "Test";

            memberList.Add(member);

            Save();
        }

        static void Save()
        {
            String json = JsonConvert.SerializeObject(memberList);
            System.IO.File.WriteAllText(filename, json);
        }

        static void Load()
        {
           memberList = JsonConvert.DeserializeObject<List<FacultyMember>>(System.IO.File.ReadAllText(filename));
            AddNew();
            Save();
        }
    }

答案 1 :(得分:0)

有几件事:

  1. 您需要反序列化为您想要的对象类型然后转换结果(在本例中为FacultyMembers数组。
  2. 当您从文件中读取时,您应该使用using语句将其包围,以便关闭。
  3. 以下是一个示例:

    using System;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    
    public class Foo
    {
        static String filename = @"C:\test.json";
    
        public static void Save()
        {
            FacultyMember member = new FacultyMember();
    
            member.firstName = Guid.NewGuid().ToString();
            member.lastName = "Bar";
            member.email = "Email";
            member.ext = "Ext";
            member.department = "Dept";
    
            List<FacultyMember> existing = new List<FacultyMember>(); 
            existing.AddRange(Load());
    
            existing.Add(member);
    
            String json = JsonConvert.SerializeObject(existing.ToArray());
            System.IO.File.WriteAllText(filename, json);
        }
    
        public static FacultyMember[] Load()
        {
            if (System.IO.File.Exists(filename))
            {
                using (System.IO.StreamReader re = new System.IO.StreamReader(filename))
                {
                    JsonTextReader reader = new JsonTextReader(re);
                    JsonSerializer se = new JsonSerializer();
                    object obj = se.Deserialize(reader, typeof (FacultyMember[]));
                    return (FacultyMember[]) obj;
                }
            }
            return new FacultyMember[0];
        }
    }
    
    public class FacultyMember
    {
        public String firstName { get; set; }
        public String lastName { get; set; }
        public String email { get; set; }
        public String ext { get; set; }
        public String department { get; set; }
    
        public FacultyMember()
        {
    
        }
    }