在 C# 中将值格式化为有效的 json 文件

Format values as a valid json file in C#

我正在尝试使用 C# 以有效的方式以有效的 JSON 格式编写行 文件应该是什么样子:

[
  {
    "uuid": "c92161ba-7571-3313-9b59-5c615d25251c",
    "name": "thijmen321"
  },
  {
    "uuid": "3b90891d-e6fc-44cc-a1a8-e822378ec148",
    "name": "TehGTypo"
  },
  {
    "uuid": "5f820c39-5883-4392-b174-3125ac05e38c",
    "name": "CaptainSparklez"
  }
]

我已经有了名称和 UUID,但我需要一种将它们写入文件的方法。我想一个一个地做这个,所以,首先文件看起来像这样:

[
  {
    "uuid": "c92161ba-7571-3313-9b59-5c615d25251c",
    "name": "thijmen321"
  }
]

然后像这样:

[
  {
    "uuid": "c92161ba-7571-3313-9b59-5c615d25251c",
    "name": "thijmen321"
  },
  {
    "uuid": "3b90891d-e6fc-44cc-a1a8-e822378ec148",
    "name": "TehGTypo"
  }
]

等但是当然,UUID 和名称是不同的,那么我怎样才能在不使用任何 API 等的情况下以有效的方式做到这一点呢? 我当前的(非常低效的)代码:

public void addToWhitelist()
{
    if (String.IsNullOrEmpty(whitelistAddTextBox.Text)) return;
    string player = String.Empty;

    try
    {
        string url = String.Format("https://api.mojang.com/users/profiles/minecraft/{0}", whitelistAddTextBox.Text);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
        request.Credentials = CredentialCache.DefaultCredentials;

        using (WebResponse response = request.GetResponse())
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            player = reader.ReadToEnd();
    }
    catch (WebException ex)
    {
        Extensions.ShowError("Cannot connect to http://api.mojang.com/! Check if you have a valid internet connection. Stacktrace: " + ex, MessageBoxIcon.Error);
    }
    catch (Exception ex)
    {
        Extensions.ShowError("An error occured! Stacktrace: " + ex, MessageBoxIcon.Error);
    }

    if (String.IsNullOrWhiteSpace(player)) { Extensions.ShowError("This player doesn't seem to exist.", MessageBoxIcon.Error); return; }
    player = player.Replace(",\"legacy\":true", "")
    .Replace("\"id", "    \"uuid")
    .Replace("\"name", "    \"name")
    .Replace(",", ",\n")
    .Replace("{", "  {\n")
    .Replace("}", "\n  },");

    File.WriteAllText(Program.programPath + @"\Servers\" + servers[currentIndex].Name + @"\whitelist.json", "");

    try
    {
        using (StreamWriter sw = File.AppendText(Program.programPath + @"\Servers\" + servers[currentIndex].Name + @"\whitelist.json"))
        {
            sw.WriteLine("[");
            foreach (string s in File.ReadAllLines(Program.programPath + @"\Servers\" + servers[currentIndex].Name + @"\whitelist.json"))
                if (s.Contains("[") || s.Contains("]") || s.Equals(Environment.NewLine)) continue;
                else sw.WriteLine(s);
            sw.WriteLine(player);
            sw.WriteLine("]");

            whitelistListBox.Items.Add("\n" + whitelistAddTextBox.Text);
        }
    }
    catch (Exception ex) { Extensions.ShowError("An error occured while update whitelist.json! Stacktrace: " + ex); }
    whitelistAddTextBox.Clear();
}

尝试 json.net 它会为您完成序列化工作:http://www.newtonsoft.com/json

我会使用 JSON 序列化程序,例如 http://www.newtonsoft.com/json

这将允许您将 uuid/name 滚动为 class,而不是自己进行解析

所以像这样:

internal class UuidNamePair 
{
  string Uuid { get; set; }
  string Name { get; set; }
}

那么在调用这个的时候,你只需要做这样的事情:

List<UuidNamePair> lst = new List<UuidNamePair>();
lst.Add(new UuidNamePair() { Name = "thijmen321", Uuid = "c92161ba-7571-3313-9b59-5c615d25251c" });
lst.Add(new UuidNamePair() { Name = "TehGTypo", Uuid = "3b90891d-e6fc-44cc-a1a8-e822378ec148" });
string json = JsonConvert.SerializeObject(lst, Formatting.Indented);
Console.WriteLine(json);

您可以 POST 代替 Console.WriteLine 到网络服务,或者您尝试使用此 json。

推荐的 "Microsoft" 方法是使用数据协定和 DataContractJsonSerializer.. 请参阅此处

https://msdn.microsoft.com/de-de/library/system.runtime.serialization.json.datacontractjsonserializer%28v=vs.110%29.aspx

联系人的示例是:

[DataContract]
internal class Person
{
    [DataMember]
    internal string name;

    [DataMember]
    internal string Uuid ;
}

您按以下方式使用 class(显然)

 Person p = new Person();
 p.name = "John";
 p.Uuid = "3b90891d-e6fc-44cc-a1a8-e822378ec148";

并使用 Contract Serializer 将其序列化

  MemoryStream stream1 = new MemoryStream();
  DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
ser.WriteObject(stream1, p);

显示序列化数据的示例:

  stream1.Position = 0;
  StreamReader sr = new StreamReader(stream1);
  Console.WriteLine(sr.ReadToEnd());