【发布时间】:2015-06-16 08:46:28
【问题描述】:
我正在尝试使用 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 序列化器,而不是尝试使用字符串自己执行此操作。
标签: c# json minecraft whitelist