在 C# 类中定义字典

本文关键字:定义 字典 | 更新日期: 2023-09-27 17:56:32

我有一个.json文件,我想用C#读取。

Json 文件如下所示:

{"SN0124":{
    "category1": 0,
    "output": {
        "ABC": [], 
        "DEF": 0, 
        "GHI": "ABDEF"
    },
    "category2": 0, 
    "category3": 0
},
"SN0123":{
    "category1": 0, 
    "output": {
        "ABC": ["N1", "N2"], 
        "DEF": 0, 
        "GHI": "ABDEF"
    },
    "category2": 0, 
    "category3": 0
}

最初,输出字段不存在,我用于读取 Json 文件的自定义类如下所示:

namespace Server.Models
{
    public class Pets
    {
        public string category1 { get; set; }
        public string category2 { get; set; }
        public string category3 { get; set; }
    }
}

输出是最近添加的,我不确定如何将该字典包含在类文件中,以便我可以读取 json 文件。任何帮助将不胜感激。

谢谢!

在 C# 类中定义字典

这应该可以正常工作。我基本上创建了一个名为 Output 的新类,其中包含预期的 JSON 字段。我还将类别字段的类型编辑为 int。

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string JSONInput = @"{""SN0124"": {
                                    ""category1"": 0,
                                    ""output"": {
                                        ""ABC"": [], 
                                        ""DEF"": 0, 
                                        ""GHI"": ""ABDEF""
                                    },
                                    ""category2"": 0, 
                                    ""category3"": 0
                                },
                                ""SN0123"": {
                                    ""category1"": 0, 
                                    ""output"": {
                                        ""ABC"": [""N1"", ""N2""], 
                                        ""DEF"": 0, 
                                        ""GHI"": ""ABDEF""
                                    },
                                    ""category2"": 0, 
                                    ""category3"": 0
                                }}";
            Dictionary<string, Pets> deserializedProduct = JsonConvert.DeserializeObject<Dictionary<string, Pets>>(JSONInput);
            Console.ReadKey();
        }
    }
    public class Output
    {
        public string[] ABC { get; set; }
        public int DEF { get; set; }
        public string GHI { get; set; }
    }
    public class Pets
    {
        public int category1 { get; set; }
        public Output output { get; set; }
        public int category2 { get; set; }
        public int category3 { get; set; }
    }
}

我不确定我是否完全理解你的意思。如果我理解正确,您是在尝试将output中的值保存在字典中?

您可以执行以下操作:

var output = new Dictionary<string, string[]>();

但是,创建自定义类来保存该数据结构可能更简单。