[英]Defining a dictionary in a C# class
我有一个要在C#中读取的.json文件。
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文件。 任何帮助将不胜感激。
谢谢!
这应该工作正常。 我基本上已经创建了一个名为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[]>();
但是创建一个自定义类来保存数据结构可能更简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.