在C#中将数据附加到json文件中 [英] Append data in a json file in C#

查看:741
本文介绍了在C#中将数据附加到json文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何继续添加数据? 我有这个:

How would i keep appending data? I have this:

{
  "13232": [
    "2012952"
  ]
}

我想向其添加另一个对象,例如:

And i want to add an another object to it, example:

{
  "13232": [
    "2012952"
  ],
  "19213": [
    "2016086"
  ]
}

这是我使用的代码:

JArray array = new JArray();
array.Add(Itemid);

JObject o = new JObject();
o[Userid] = array;

string json = o.ToString(Formatting.Indented);
//i know this keeps appending text but how would i append it inside the { and }?
File.AppendAllText("E:/media.json", json);

我真的不知道如何继续添加它,但是也许其他人知道吗?

I literally have no idea how to keep adding it, but maybe someone else has?

推荐答案

您将无法使用文件追加操作来执行此操作.文件追加操作只能在末尾添加文本,而不能在中间的某个位置插入文本.这使得不可能使用file-append来保持JSON有效.

You won't be able to use file append operations to do this. File append operations can only add text to the end, they can't insert text at some point in the middle. This makes it impossible to use file-append to keep the JSON valid.

您有两种选择,我可以想到:

You have two choices that I can think of:

  1. 将整个文件读入一个对象,添加您的对象,然后 重写整个文件(性能不佳)
  2. 打开文件读/写,解析通过 直到您到达右大括号为止,然后写下其余的 数据,然后写上紧紧的花括号(不平凡)
  1. Read the entire file into an object, add your object, and then rewrite the entire file (poor performance)
  2. Open the file read/write, parse through until you get to the closing curly brace, then write the remaining data, then write the close curly brace (not trivial)

这篇关于在C#中将数据附加到json文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆