0
我正在通過讀取對象列表中的一些數據,將其轉換爲嵌套字典並序列化結果來創建JSON文件。所需的JSON格式如下:在將列表轉換爲字典時獲取重複的JSON項目
{
"Employee1": {
"YYY": {
"StartRange": 11,
"EndRange": 22
}
},
"Employee2": {
"XXX": {
"StartRange": 24,
"EndRange": 56
}
}
}
但我得到這個JSON輸出,而不是:
{
"Employee1": {
"YYY": {
"StartRange": 11,
"EndRange": 22
},
"XXX": {
"StartRange": 11,
"EndRange": 22
}
},
"Employee2": {
"YYY": {
"StartRange": 24,
"EndRange": 56
},
"XXX": {
"StartRange": 24,
"EndRange": 56
}
}
}
這裏是我使用的代碼:
public class LabelData
{
public int StartRange { get; set; }
public int EndRange { get; set; }
}
public class ConfigInfo
{
public string ParentGroup;
public string Label;
public int ID;
public int StartRange;
public int EndRange;
}
public Dictionary<string, Dictionary<string, LabelData>> GetData(List<ConfigInfo> configList)
{
var labelData = new Dictionary<string, Dictionary<string, LabelData>>();
foreach (var listItem in configList)
{
labelData[listItem.ParentGroup] = configList.Distinct().ToDictionary(x => x.Label.ToString(), row => new LabelData()
{
StartRange = Convert.ToInt32(listItem.StartRange.ToString()),
EndRange = Convert.ToInt32(listItem.EndRange.ToString())
});
}
return labelData;
}
protected void createFile()
{
List<ConfigInfo> configInfoList = new List<ConfigInfo>();
ConfigInfo configInfo = new ConfigInfo();
configInfo.ParentGroup = "Employee1";
configInfo.StartRange = 11;
configInfo.EndRange = 22;
configInfo.Label = "YYY";
configInfoList.Add(configInfo);
configInfo = new ConfigInfo();
configInfo.ParentGroup = "Employee2";
configInfo.StartRange = 24;
configInfo.EndRange = 56;
configInfo.Label = "XXX";
configInfoList.Add(configInfo);
if (!File.Exists(fileName))
{
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
JsonTextWriter writer = new JsonTextWriter(sw);
Dictionary<string, Dictionary<string, LabelData>> data = GetData(configInfoList);
string json = JsonConvert.SerializeObject(data,Formatting.Indented);
sw.Write(json);
sw.Close();
}
}
我覺得問題可能與兩個類中都有StartRange和EndRange有關,但我不知道如何解決它。我究竟做錯了什麼?
我不明白你的要求。在最終期望的輸出中,您希望Employee1的Label,StartRange和EndRange顯示在Employee2下,並且您希望Employee2的Label,StartRange和EndRange顯示在Employee1下面?如果列表中有三名員工而不是2名,會發生什麼情況?如果只有1個呢? –
如果有一個僱員的輸出將是 – Vinoth
如果有一個僱員的輸出將是{ 「Employee1」:{ 「YYY」:{ 「StartRange」:11, 「EndRange」:22 } } }如果有三個員工輸出將是{ 「Employee1」:{ 「YYY」:{ 「StartRange」:11, 「EndRange」:22 } }, 「和Employee2」:{ 「 YYY「:{ 」StartRange「:24, 」EndRange「:56 } }, 「Employee3」: 「AAA」:{ 「StartRange」:56, 「EndRange」:99 } } – Vinoth