我正在使用json.NET在asp.net中使用json,其中来自textbox的按钮点击值被添加到名为country.json的json文件中。有两个文本框,以国家及其资本为价值, country.json文件看起来像这样,
[
{
"country":"USA",
"capital":"New York"
},
{
"country":"China",
"capital":"Bejing"
},
{
"country":"India",
"capital":"New Delhi"
}
]
我能够用一个节点创建json,但是如何将第二个节点附加到现有的json。 这是c#代码,
public class country
{
public string Country { get; set; }
public string Capital { get; set; }
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
country ctry = new country();
ctry.Country = txtCtry.Text;
ctry.Capital = txtCapital.Text;
File.AppendAllText(MapPath("Data/countrycaps.json"),JsonConvert.SerializeObject(ctry,Formatting.Indented));
}
答案 0 :(得分:3)
如果你想要一个列表,你应该保存一个列表,而不是一个节点。
以下是步骤:
答案 1 :(得分:2)
我需要相同的功能,往返太贵了。 这就是我想出的:
private static void AppendTransaction(Transaction transaction)
{
const string filename = "transactions.json";
bool firstTransaction = !File.Exists(filename);
JsonSerializer ser = new JsonSerializer();
ser.Formatting = Formatting.Indented;
ser.TypeNameHandling = TypeNameHandling.Auto;
using (var fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
{
Encoding enc = firstTransaction ? new UTF8Encoding(true) : new UTF8Encoding(false);
using (var sw = new StreamWriter(fs, enc))
using (var jtw = new JsonTextWriter(sw))
{
if (firstTransaction)
{
sw.Write("[");
sw.Flush();
}
else
{
fs.Seek(-Encoding.UTF8.GetByteCount("]"), SeekOrigin.End);
sw.Write(",");
sw.Flush();
}
ser.Serialize(jtw, transaction);
sw.Write(']');
}
}
}