如何反序列化json?

时间:2015-07-12 15:12:51

标签: .net json vb.net serialization token

我的应用程序使用配置管理游戏的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寻求帮助。

1 个答案:

答案 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)

有一些改进和注意事项:

  1. 存储路径文字时,不要使用转义字符。使用"C:\path\file\..."而不是"C:\\path\\file\\..."。序列化程序添加了额外的\ s
  2. 如上所述,我不会解析Enabled以确定全屏,而是使用Booleam。
  3. 我会避免使用破折号,斜线和空格等名称和键
  4. 有些内容可能更好,例如枚举或类型,"MCF_1.0",因此您无需解析它以确定它是11.1还是{{1 }}
  5. 由于配置在字典中,如果您不熟悉它们,您可能想要了解如何使用它们。