如何反序列化扩展的 JSON 文件?

问题描述

如何将该 JSON 文件反序列化为 C# 对象?

{
   "arch": {
      "name": "Arch Linux","source": "image"
   },"ubuntu": {
     "name": "Ubuntu","source": "image"
   }
}

解决方法

//using Newtonsoft.Json;

你可以做到

    string json = @"{
           'arch': {
              'name': 'Arch Linux','source': 'image'
           },'ubuntu': {
             'name': 'Ubuntu','source': 'image'
           }
        }";

    Dictionary<string,Settings> config =
        JsonConvert.DeserializeObject<Dictionary<string,Settings>>(json);

Settings 这样的类:

public class Settings
{
    public string Name { get; set; }
    public string Source { get; set; }
}

您需要安装 Newtonsoft.Json NuGet 包。怎么样,看这个https://docs.microsoft.com/en-us/nuget/quickstart/install-and-use-a-package-in-visual-studio

,

@UsemeAlehosaini 响应中可能存在错误。您的解决方案很可能不起作用,因为 Settings 类与您尝试反序列化的 JSON 结构不匹配。

public class Arch
{
    public string Name { get; set; }
    public string Source { get; set; }
}

public class Ubuntu
{
    public string Name { get; set; }
    public string Source { get; set; }
}

public class Example
{
    public Arch Arch { get; set; }
    public Ubuntu Ubuntu { get; set; }
}

@JakubWrobel 你能试试把这些类而不是设置吗?