[英]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.