如何在不删除先前数据的情况下插入json文件?

时间:2018-09-22 14:39:46

标签: c# json json.net

我正在将数据插入.json文件中。我的插入工作正常,但是有一个问题-插入新数据时,文件中的先前数据将被删除。 我该如何处理? 另外,我还需要采用以下格式:

[
  {
    "Rollnumber": 3,
    "StudentName": "Tapas"
  },
  {
    "Rollnumber": 4,
    "StudentName": "Papas"
  }
]

当我将数据作为list.ToArray()(在代码示例中为_data)传递时,我得到了[]括号,但仅在rollnumber = 3的第一个数据上。 到目前为止,这是我的代码:

private void AddStudent()
{
    Student objStudent = new Student();
    objStudent.Rollnumber = 3;
    objStudent.StudentName = "Tapas";


    /*  List<Student> _data = new List<Student>();
    _data.Add(new Student()
    {
        Rollnumber = 4,
        StudentName = "Papas"
    });
    */

    string jsonData = JsonConvert.SerializeObject(objStudent, Formatting.Indented);
    System.IO.File.WriteAllText(jsonFileS, jsonData);
}

我也尝试过StreamWritter,但我做不到。

4 个答案:

答案 0 :(得分:2)

  1. 检索包含JSON的源文件。
  2. 从源文件读取文本内容(JSON数据)。
  3. 将JSON数据反序列化为学生对象列表。
  4. 添加新的学生名单。
  5. 序列化学生列表,您将获得JSON数据字符串作为该方法的返回。
  6. 将JSON字符串保存到源文件中。

这是示例代码:

var file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
var jsonString = await FileIO.ReadTextAsync(file);
var studentList = JsonConvert.DeserializeObject<List<Student>>(jsonString);
var newStudent = new Student();
newStudent.Rollnumber = 2;
newStudent.StudentName = "Abcd";
studentList.Add(newStudent);
var updatedJsonString = JsonConvert.SerializeObject(studentList);
await FileIO.WriteTextAsync(file, updatedJsonString);

答案 1 :(得分:1)

我认为在您的情况下,您可以做一些小技巧:

1,从文件中读取数据

StreamReader sw = new StreamReader(fileName);
string res = sw.ReadToEnd();

2,删除“ res”(res变量)的“]”并添加新的Json字符串(删除“ [”并添加“,”),并使用您的格式。

因此,您的字符串看起来就像是两个波纹管一起加起来

[
  {
    "Rollnumber": 3,
    "StudentName": "Tapas"
  }
// Cut the last "]"

// cut the first "[" and add ","
      ,
      {
        "Rollnumber": 4,
        "StudentName": "Papas"
      }
    ]

因此它将成为您最终想要的:

[
  {
    "Rollnumber": 3,
    "StudentName": "Tapas"
  },
  {
    "Rollnumber": 4,
    "StudentName": "Papas"
  }
]   

答案 2 :(得分:1)

答案在此链接上:append to a json file

TestClass.Equals(TestClass)

答案 3 :(得分:1)

正如我在对问题的评论中提到的那样,您需要加载整个文件,将其反序列化,然后在内存中添加项目。完成后,通过序列化将其重写。

如果您不想将整个文件加载到内存中,请通过操作序列化的字符串然后附加到文件来手动使用该文件;否则您将在文件中得到错误的JSON。

这是您反序列化整个文件的第一种方法:

public static class Program
{
    public static void Main()
    {
        var rolls = LoadRolls();

        // Once the contents of the file are in memory you can also manipulate them         
        Roll firstRoll = rolls.SingleOrDefault(x => x.Rollnumber == 1);
        if (firstRoll != null)
        {
            firstRoll.StudentName = "Jerry";
        }

        // Let's just add a few records. 
        rolls.AddRange(
            new List<Roll>{
                new Roll { Rollnumber = 1, StudentName = "Elaine" },
                new Roll { Rollnumber = 2, StudentName = "George" }
            });

        string json = JsonConvert.SerializeObject(rolls, Newtonsoft.Json.Formatting.Indented);

        File.WriteAllText("Rolls.txt", json);

        Console.Read();
    }

    private static List<Roll> LoadRolls()
    {
        List<Roll> rolls = JsonConvert.DeserializeObject<List<Roll>>(File.ReadAllText("Rolls.txt"));

        return rolls ?? new List<Roll>();
    }
}

public class Roll
{
    public int Rollnumber { get; set; }
    public string StudentName { get; set; }
}