如何列出所有我的世界配置文件
本文关键字:我的世界 配置文件 何列出 | 更新日期: 2023-09-27 18:36:43
如何通过 launcher_profiles.json 文件列出所有 minecraft 配置文件?
我尝试使用该站点 json2csharp.com,但不幸的是,当它生成类就绪代码时,他返回了所有配置文件,就好像它也是一个类一样。
例如:我使用了这个简单的代码我的世界配置文件...
{
"profiles": {
"1.7.10": {
"name": "1.7.10",
"lastVersionId": "1.7.10"
}
},
"selectedProfile": "1.7.10"
}
但是当我发送站点以转换 C# 时,它会返回以下内容:
public class __invalid_type__1710
{
public string name { get; set; }
public string lastVersionId { get; set; }
}
public class Profiles
{
public __invalid_type__1710 __invalid_name__1.7.10 { get; set; }
}
public class RootObject
{
public Profiles profiles { get; set; }
public string selectedProfile { get; set; }
}
亲眼看看: Json2CSharp
你有没有办法使用 Newtonsoft.Json.Linq 读取 launcher_profiles.json 文件 minecraft?
虽然在许多情况下很有用,但 json2csharp.com 并非万无一失。 如您所见,它不处理键名称是动态的或无法转换为有效 C# 标识符的情况。 在这些情况下,您需要对生成的类进行手动调整。 例如,可以使用 Dictionary<string, Profile>
代替静态类来处理 profiles
对象的动态键。
像这样定义类:
public class RootObject
{
public Dictionary<string, Profile> profiles { get; set; }
public string selectedProfile { get; set; }
}
public class Profile
{
public string name { get; set; }
public string lastVersionId { get; set; }
}
然后,可以使用 JavaScriptSerializer
或 Json.Net(以您喜欢的方式)反序列化为 RootObject
类。
这是使用 Json.Net 的小提琴:https://dotnetfiddle.net/ZlEK63
所以问题可能是 launcher_profiles.json 并不是真正的犹太洁食 JSON。
把它放到 Json2CSharp 中,看看我的意思:
{
"profiles": [
{
"name": "1.7.10",
"lastVersionId": "1.7.10"
}
],
"selectedProfile": "1.7.10"
}
这里的区别在于,我重新定义了配置文件节点,以正确表示映射到 C# 中泛型列表的集合(数组)。
您可能需要手动解析该文件,因为 JSON.Net 否则其他选项将无法处理无效的 json 格式。
我通常不使用 Json.Net 库的 Linq 版本,但我提出了一个简单的示例来说明如何获取配置文件的所有名称(您不能序列化为具有给定格式的类)。
class Program
{
//Add another "profile" to show this works with more than one
private static String json = "{ '"profiles'": { '"1.7.10'": { '"name'": '"1.7.10'", '"lastVersionId'": '"1.7.10'" }, '"1.7.11'": { '"name'": '"1.7.11'", '"lastVersionId'": '"1.7.11'" } }, '"selectedProfile'": '"1.7.10'" }";
static void Main(string[] args)
{
//Parse to JObject
var obj = Newtonsoft.Json.Linq.JObject.Parse(json);
foreach (var profile in obj["profiles"])
{
foreach (var child in profile.Children())
{
Console.WriteLine(child["name"]);
}
}
}
}