【问题标题】:Format values as a valid json file in C#在 C# 中将值格式化为有效的 json 文件
【发布时间】: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


【解决方案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】:

    我会使用像 http://www.newtonsoft.com/json 这样的 JSON 序列化器

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

    比如:

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

    除了 Console.WriteLine,您可以将 POST 发送到 Web 服务,或者您尝试使用此 json。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • “那么我怎样才能在不使用任何 API 等的情况下以有效的方式做到这一点?”
      猜你喜欢
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 2018-07-06
      • 2015-08-19
      • 1970-01-01
      相关资源
      最近更新 更多