简体   繁体   English

如何将 JSON object 列表序列化到文件中,其中 c# 不是数组

[英]how to serialize JSON object lists into file with c# not array

I have this code right here to add a piece of JSON to a file, but instead of working it makes an array with [] breaking how my file is read.我在这里有这段代码,可以将一段 JSON 添加到文件中,但是它没有使用 [] 来创建一个数组,从而破坏了我的文件的读取方式。

var serverid = ctx.Guild.Id.ToString();
List<data> _data = new List<data>();
_data.Add(new data() {
    mute = $"{Role.Name}"
});
string json = JsonConvert.SerializeObject(_data.ToList());
File.WriteAllText(@$".\serverconfigs\{serverid}.json", json);

That's not a valid json.这不是有效的 json。 You would need to create a class with an array.您需要使用数组创建 class。 Then when you serialize that class it would be serialized like this:然后,当您序列化 class 时,它将像这样序列化:

{"_data":[{"mute":"CobraMute"}]} {"_data":[{"mute":"CobraMute"}]}

In your code, it would be like this:在您的代码中,它将是这样的:

class Program
{
    YourClass myclass = new YourClass();
    myclass._data = new List<data>();
    myclass._data.Add(new data()
    {
        mute = $"{Role.Name}"
    });
    string json = JsonConvert.SerializeObject(myclass);
    File.WriteAllText(@$".\serverconfigs\{serverid}.json", json);
}
class YourClass{
    public List<data> _data;
}

To create your JSON without square brackets, simply omit the list when you serialize:要创建不带方括号的 JSON,只需在序列化时省略该列表:

var _data = new data() {
    mute = $"{Role.Name}"
};
string json = JsonConvert.SerializeObject(_data);
File.WriteAllText(@$".\serverconfigs\{serverid}.json", json);

This will generate: {"mute": "CobraMute"} assumuing that Role.Name is CobraMute这将生成: {"mute": "CobraMute"}假设Role.NameCobraMute

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM