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

时间:2015-04-10 15:00:06

标签: c# json minecraft whitelist

我正在尝试以有效的方式使用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();
}

3 个答案:

答案 0 :(得分:1)

尝试json.net它将为您执行序列化工作:http://www.newtonsoft.com/json

答案 1 :(得分:1)

推荐的“微软”方式是与数据合同和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 ;
}

您以下列方式使用该类(显然)

 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());

答案 2 :(得分:0)

我会使用像http://www.newtonsoft.com/json

这样的JSON序列化程序

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

类似于:

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发送到Web服务,或者尝试使用此json,而不是Console.WriteLine。