我的应用程序使用配置管理游戏的modpacks,因此配置加载程序以这种方式工作:
这是configurations.json:
{
"GameDirectory": "C:\\Users\\username\\AppData\\Roaming\\.mp-craft-project",
"Configurations": {
"MP-Craft-Default": {
"Name": "MP-Craft-Default",
"JavaPath": "C:\\ProgramFiles\\Java\\jre-xxx\\bin\\javaw.exe",
"FullScreenMode": "Enabled",
"ModLoader": "MCF_1.0"
},
"New-Configuration": {
"Name": "New-Configuration",
"JavaPath": "C:\\ProgramFiles\\Java\\jre-xxx\\bin\\javaw.exe",
"FullScreenMode": "Enabled",
"ModLoader": "MCF_2.0"
}
}
}
此json中的字符串(例如modloader或fullscreenmode)可以是相同或不同(未知)的变体。 我想按名称加载所有配置,并加载所选配置的设置。有人可以帮助我,我怎样才能将这个json反序列化。
我使用Newtonsoft.Json
进行反序列化。
THX寻求帮助。
答案 0 :(得分:1)
您需要2个类,一个包含Config集合和各种“全局”数据,然后是一个类的项目:
Public Class Configs
Public Property GameDirectory As String
Public Property Configurations As Dictionary(Of String, ConfigItem)
Public Sub New()
Configurations = New Dictionary(Of String, ConfigItem)
End Sub
End Class
Public Class ConfigItem
Public Property Name As String
Public Property JavaPath As String
Public Property FullScreenMode As String ' I would use Boolean
Public Property ModLoader As String
End Class
创建集合类并将配置项存储到它:
Imports System.Environment
...
Dim myCfgs As New Configs
myCfgs.GameDirectory = Path.Combine(Environment.GetFolderPath(SpecialFolder.ApplicationData), ".mp-craft-project")
Dim p As New ConfigItem
p.Name = "Ziggy"
p.FullScreenMode = "Enabled"
p.ModLoader = "MCF_1.0"
p.JavaPath = "C:\ProgramFiles\Java\jre-xxx\bin\javaw.exe"
' add this item to the collection
myCfgs.Configurations.Add(p.Name, p)
' add another, create a new ConfigItem object
p = New ConfigItem
p.Name = "Hoover"
p.FullScreenMode = "Enabled"
p.ModLoader = "MCF_2.0"
p.JavaPath = "...javaw.exe"
myCfgs.Configurations.Add(p.Name, p)
要从集合中选择一个使用:
Dim thisCfg As ConfigItem = myCfgs.Configurations("Ziggy")
Console.WriteLine("Name: {0}, JavaPath: {1}, ModLoader: {2}",
thisCfg.Name, thisCfg.JavaPath, thisCfg.ModLoader)
输出:
名称:Ziggy,JavaPath:C:\ ProgramFiles \ Java \ jre-xxx \ bin \ javaw.exe,ModLoader:MCF_1.0
序列化/保存它:
' save all configs to disk:
Dim jstr = JsonConvert.SerializeObject(myCfgs)
File.WriteAllLines(saveFileName, jstr)
加载最后一组保存的配置:
' load the text, then deserialize to a Configs object:
Dim jstr = File.ReadAllText(saveFileName)
Dim myCfgs As Configs = JsonConvert.DeserializeObject(Of Configs)(jstr)
有一些改进和注意事项:
"C:\path\file\..."
而不是"C:\\path\\file\\..."
。序列化程序添加了额外的\
s Enabled
以确定全屏,而是使用Booleam。"MCF_1.0"
,因此您无需解析它以确定它是1
,1.1
还是{{1 }}